RAII pointers

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 29 17:31:13 PDT 2017


On Monday, 29 May 2017 at 23:39:17 UTC, Russel Winder wrote:
> C++ allows one to create types that are pointer types but wrap 
> a primitive pointer to give RAII handling of resources. For 
> example:
>
>
>     class Dvb::FrontendParameters_Ptr {
>     private:
>     	    dvb_v5_fe_parms * ptr;
>     public:
>     	    FrontendParameters_Ptr(FrontendId const & fei, 
> unsigned int const verbose = 0, unsigned int const legacy = 0);
>     	    FrontendParameters_Ptr(FrontendParameters_Ptr const &) 
> = delete;
>     	    FrontendParameters_Ptr & 
> operator=(FrontendParameters_Ptr const &) = delete;
>     	    ~FrontendParameters_Ptr() {dvb_fe_close(ptr); }
>     	    dvb_v5_fe_parms * c_ptr() const { return ptr; }
>     	    dvb_v5_fe_parms * operator->() const { return ptr; }
>     };
>
>
> Has anyone any experience of doing the analogous thing 
> idiomatically in D.

Yes, I generally use structs with `@disable this(this)` and 
std.algorithm.mutation.move for this.

Something like (untested, but general approach):
---
module dvb;

struct FrontendParameters_Ptr {
private:
     dvb_v5_fe_parms* ptr;
public:
     @disable this(this);
     this(ref const FrontendId fei, const uint verbose = 0, const 
uint legacy = 0) { ... }
     ~this() { dvb_fe_close(ptr); }
     auto c_ptr() const { return ptr; }
     alias c_ptr this;
}
---

Be aware that the above deliberately prohibits normal struct copy 
construction, so there is always only a single struct object. 
"Borrow" it via ref / ref const or std.algorithm.mutation.move it 
to change the owner. Or wrap this struct itself in a lifetime 
management struct (such as std.typecons.RefCounted) if you need 
multiple owners.


More information about the Digitalmars-d-learn mailing list