简体   繁体   English

是否有使用复制构造函数和赋值运算符复制对象的智能指针?

[英]Is there a smart pointer that copies the object with copy constructor and assignment operator?

In Qt, most classes usually have a public wrapper class with a single pointer to a private class.在 Qt 中,大多数类通常都有一个公共包装类,其中包含一个指向私有类的指针。 This is for binary compatibility.这是为了二进制兼容性。

https://wiki.qt.io/D-Pointer https://wiki.qt.io/D-Pointer

However this means that there are a lot of things that need to be implemented by hand.然而,这意味着有很多事情需要手动实现。 Some people suggest using a QScopedPointer.有些人建议使用 QScopedPointer。

How to use the Qt's PIMPL idiom? 如何使用 Qt 的 PIMPL 成语?

However, this does not implement copy and assignment either.但是,这也没有实现复制和赋值。 Isn't there a smart pointer that will just copy the content of the pointer when it's copied.是不是有一个智能指针,当它被复制时,它只会复制指针的内容。 In essence, it should behaves as if the data in the private class were in the public class.本质上,它应该表现得好像私有类中的数据在公共类中一样。

Qt offers a class just for this purpose: QSharedDataPointer Qt为此提供了一个类: QSharedDataPointer

Used with QSharedData it offers a fast way to implement a class with implicitly shared data and copy on write behavior. QSharedData使用时,它提供了一种使用隐式共享数据实现类并在写入行为时进行复制的快速方法。

You can also do explicit sharing with QExplicitlySharedDataPointer . 您还可以使用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;
};

The QScopePointer is the equivalent of the std::unique_ptr, it's a pointer with unique ownership, meaning that it can not be copied. QScopePointer等同于std :: unique_ptr,它是具有唯一所有权的指针,这意味着它不能被复制。

What usually you do is a deep copy of what the ScopedPointer is pointing to when you implement the copy operation of the facade. 当您实现外观的复制操作时,通常要做的是ScopedPointer指向的内容的深层副本。

Another solution is to have the pimpl implemented with a shared pointer (QSharedPointer) ; 另一个解决方案是使用共享指针(QSharedPointer)来实现pimpl; but that means that a facade copied from another will point point to the same pimpl. 但这意味着从另一个复制的外观将指向相同的pimpl。 In some scenarios that can be relevant. 在某些情况下可能是相关的。

In Qt you don't need to support copy and assignment often. 在Qt中,您不需要经常支持复制和分配。

Many classes are inherited from QObject, this inheritance, among other things, prohibits copying and assignment. 许多类都从QObject继承,这种继承除其他外禁止复制和赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM