postblit构造函数是否仅因源而与复制构造函数不同

Does postblit constructor differ only by source from copy constructor?

本文关键字:构造函数 复制 是否 postblit      更新时间:2023-10-16

如果我正确理解D中的postblit构造函数从按位复制开始(总是),那么它有用户定义的主体。

但是当我查看postblit构造函数的主体时,它与c++复制构造函数非常相似,唯一的区别是在c++中源是某个对象,而在D中是this(自身)。

我说的对吗?

嗯,结束。我认为你已经掌握得很好了,但是要把它拼出来:

a = b;(如果a和b都是同一类型,一个结构体)翻译成:

memcpy(&a, &b, b.sizeof); // bitwise copy
a.__postblit(); // call the postblit on the destination only (iff this(this) is defined on the type!)

所以你不需要显式地在postblit中分配任何变量(它们都是自动复制的),也不能用它来实现移动语义(你不能访问源代码)。

我最常使用postblit的地方是当结构体是指向另一个对象的指针时,所以我可以增加refcount:

struct S {
    SomeObject* wrapped;
    this(this) { if(wrapped) wrapped.addReference(); }
    ~this() { if(wrapped) wrapped.releaseReference(); }
}

这只适用于引用,否则你将增加变量的副本!

可以(但不应该)也使用它来执行深度复制:

struct S {
   string content;
   this(this) { content = content.idup; }
}

但这实际上是一个坏主意,因为在D中,结构赋值应该是普遍便宜的,而深度复制并不便宜。通常也不需要这样做,因为垃圾收集器可以处理像double free这样的情况,而您可能希望在c++中使用这种情况。

我在D中经常使用它的另一种情况实际上是禁用它:

struct S {
   @disable this(this);
}
S a, b;
a = b; // compile error, b is not copyable

这与根本不实现postblit不同,后者让您自动实现内存。这使得赋值成为一个完全的编译错误,您可以使用它来引导用户转向另一个方法,例如移动语义:

struct S {
   int* cool;
   @disable this(this);
   S release() { auto n = cool; cool = null; return S(cool); }
}

因为a=b是被禁止的,我们现在可以强制用户使用。release方法,当他们想要重新分配它时,我们会移动。