簡體   English   中英

是否有使用復制構造函數和賦值運算符復制對象的智能指針?

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

在 Qt 中,大多數類通常都有一個公共包裝類,其中包含一個指向私有類的指針。 這是為了二進制兼容性。

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

然而,這意味着有很多事情需要手動實現。 有些人建議使用 QScopedPointer。

如何使用 Qt 的 PIMPL 成語?

但是,這也沒有實現復制和賦值。 是不是有一個智能指針,當它被復制時,它只會復制指針的內容。 本質上,它應該表現得好像私有類中的數據在公共類中一樣。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM