Disabled and enabled copy constructors and .dup
Biotronic
simen.kjaras at gmail.com
Tue Oct 24 07:56:34 UTC 2017
On Tuesday, 24 October 2017 at 07:33:43 UTC, Per Nordlöw wrote:
> If I have a `struct X` (container in my case) with disabled
> copying (postblit) and instead a .dup property, is it somehow
> possible, unsafe or not, to have `X` as a member of another
> `struct Y` with an enabled copy constructor which calls `X.dup`?
With the same approach outline in
https://forum.dlang.org/post/nakguitssvjdclpgwhmk@forum.dlang.org, it is indeed possible. In fact, simply using SuppressGC!X should enable it. Note however, that since the point of SuppressGC is to not call the object's destructor (and thus its name is poorly chosen by yours truly), you will need to do so explicitly. Updating the approach to only suppress postblits:
struct SuppressPostblit(T)
{
// Disguise T as a humble array.
private ubyte[T.sizeof] _payload;
// Create from instance of T.
this(T arg) {
_payload = *cast(ubyte[T.sizeof]*)&arg;
}
// Or forward constructor arguments to T's constructor.
static if (__traits(hasMember, T, "__ctor"))
{
this(Args...)(Args args)
if (__traits(compiles, (Args e){__traits(getMember,
T.init, "__ctor")(e);}))
{
__traits(getMember, get, "__ctor")(args);
}
}
// Pretend to be a T.
@property
ref T get()
{
return *cast(T*)_payload.ptr;
}
alias get this;
static if (__traits(hasMember, T, "__dtor")) {
~this() {
__traits(getMember, get, "__dtor")();
}
}
}
--
Simen
More information about the Digitalmars-d-learn
mailing list