postblit构造函数是否仅因源而与复制构造函数不同
Does postblit constructor differ only by source from copy constructor?
如果我正确理解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); }
}
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类