UniquePtr in D
Timon Gehr
timon.gehr at gmx.ch
Sun Dec 22 06:13:27 PST 2013
On 12/22/2013 02:19 PM, Benjamin Thaut wrote:
> When working with C-libraries in D I often wish for a equivalent of the
> C++11 unique_ptr. Unfortunately this is not possible in D. Consider the
> following source code:
>
> http://dpaste.dzfl.pl/6e71c815
>
> Is error 1 a bug? Because there should cleary not be any copy at this
> point.
> ...
I don't think the conditions when a struct is moved are actually
documented beyond the NRVO case. I think it ideally would be a bug, but
this would require some kind of DIP.
> Should we implement moving of u so that error 2 goes away? The compiler
> could move u into the function and move back out afterwards, but that
> would mean that the contents of u would be invalid for the duration of
> the function call (unsafe?)
>
> Kind Regards
> Benjamin Thaut
The problem is that currently variable 'u' needs to be valid in order to
be assigned to. It would be better if it was moved into test2 and then
reinitialized.
Currently, structs with disabled default construction and postblit are
pretty much useless as value types. One has to include some kind of
invalid default state. (As Sergei's implementation also does.) Then it
is always possible to use explicit moves:
import core.stdc.stdio;
import std.algorithm;
struct UniquePtr{
private int m_i;
private bool _valid=false;
@property bool valid(){ return valid; }
@disable this(this);
this(int i){
m_i = i;
_valid = true;
}
~this(){
if(_valid) printf("deleting %d\n", m_i);
}
}
UniquePtr test1(){
auto u = UniquePtr(5);
return u;
}
UniquePtr test2(UniquePtr u){
return move(u);
}
void main(string[] args){
auto u = test1();
u = test2(move(u));
}
More information about the Digitalmars-d
mailing list