[英]Is it necessary to block the assignment operator and the copy constructor when using smart pointers?
[英]Is there a smart pointer that copies the object with copy constructor and assignment operator?
在 Qt 中,大多数类通常都有一个公共包装类,其中包含一个指向私有类的指针。 这是为了二进制兼容性。
然而,这意味着有很多事情需要手动实现。 有些人建议使用 QScopedPointer。
但是,这也没有实现复制和赋值。 是不是有一个智能指针,当它被复制时,它只会复制指针的内容。 本质上,它应该表现得好像私有类中的数据在公共类中一样。
Qt为此提供了一个类: QSharedDataPointer
与QSharedData
使用时,它提供了一种使用隐式共享数据实现类并在写入行为时进行复制的快速方法。
您还可以使用QExplicitlySharedDataPointer
进行显式共享。
class MyData : public QSharedData
{
public:
MyData (){ }
MyData (const MyData &other)
: QSharedData(other), a(other.a), b(other.b) { }
~MyData () { }
int a;
QString b;
};
class MyClass
{
public:
MyClass() { d = new MyData; }
MyClass(const MyClass&other)
: d (other.d)
{
}
void setA(int a) { d->a = a; } // the function is non const, so accessing d->a will make a copy of MyData if d is shared with another instance (CoW)
int a() const { return d->a; }
private:
QSharedDataPointer<MyData> d;
};
QScopePointer等同于std :: unique_ptr,它是具有唯一所有权的指针,这意味着它不能被复制。
当您实现外观的复制操作时,通常要做的是ScopedPointer指向的内容的深层副本。
另一个解决方案是使用共享指针(QSharedPointer)来实现pimpl; 但这意味着从另一个复制的外观将指向相同的pimpl。 在某些情况下可能是相关的。
在Qt中,您不需要经常支持复制和分配。
许多类都从QObject继承,这种继承除其他外禁止复制和赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.