【问题标题】:Is there a smart pointer that copies the object with copy constructor and assignment operator?是否有使用复制构造函数和赋值运算符复制对象的智能指针?
【发布时间】:2023-04-01 08:40:01
【问题描述】:

在 Qt 中,大多数类通常都有一个公共包装类,其中包含一个指向私有类的指针。这是为了二进制兼容性。

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

然而,这意味着有很多事情需要手工实现。有人建议使用 QScopedPointer。

How to use the Qt's PIMPL idiom?

但是,这也没有实现复制和赋值。是不是有一个智能指针在复制指针时只会复制指针的内容。本质上,它应该表现得好像私有类中的数据在公共类中一样。

【问题讨论】:

  • 假设您有一个类A 作为类B (class B : public A) 的基类,并且您有一个按如下方式构造的作用域指针:QScopedPointer<A> (new B)。您打算如何在不丢失数据的情况下复制它(以便调用Bs 复制构造函数)?

标签: c++ qt smart-pointers


【解决方案1】:

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;
};

【讨论】:

    【解决方案2】:

    QScopePointer 相当于 std::unique_ptr,它是一个拥有唯一所有权的指针,意味着它不能被复制。

    当你实现门面的复制操作时,你通常做的是一个 ScopedPointer 指向的内容的深拷贝。

    另一个解决方案是使用共享指针 (QSharedPointer) 实现 pimpl ;但这意味着从另一个复制的外观将指向同一个 pimpl。在某些可能相关的场景中。

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2013-04-13
      相关资源
      最近更新 更多