QsharedDatapointer用于私人数据:如何编写可以删除副本的好复制操作员

问题描述 投票:0回答:1

main.cpp:


#include <QtDebug> #include "Nix.h" int main( int , char ** ) { Nix *nix1 = new Nix(1, "Hello, I'm one"); Nix *nix2 = new Nix(); nix2 = nix1; nix2->add(2, "Hello, I'm two"); Nix *nix3 = new Nix(*nix2); nix3->add(3, "Hello, I'm three"); qWarning() << "nix1: " << nix2->display(1) << nix1->display(2) << nix1->display(3); qWarning() << "nix2: " << nix2->display(1) << nix2->display(2) << nix1->display(3); delete nix2; // if nix1 is deleted, accessing nix2 will produce a segment violation qWarning() << "nix3: " << nix3->display(1) << nix3->display(2) << nix3->display(3); // segmentation fault: qWarning() << "nix1: " << nix1->display(1) << nix1->display(2) << nix1->display(3); return 0; }

NIX.H:

#include <QString> #include <QSharedDataPointer> class NixPrivate; class Nix { public: Nix(); Nix(int a, QString b); ~Nix(); Nix(Nix const &other); Nix &operator=(const Nix &other); QString display(int x); void add(int a, QString b); private: QSharedDataPointer<NixPrivate> d; };

nix.cpp

#include "Nix.h" #include <QMap> #include <QString> #include <QSharedData> class NixPrivate : public QSharedData { public: QMap<int, QString> myMap; }; Nix::Nix() : d(new NixPrivate()) { } Nix::Nix(int a, QString b) : Nix() { d->myMap[a] = b; } Nix::~Nix() { } Nix::Nix(Nix const &other) : Nix() { d = other.d; } Nix &Nix::operator=(const Nix &other) { d = other.d; return *this; } QString Nix::display(int x) { if (d->myMap.contains(x)) { return d->myMap.value(x); } else { return "not found"; } } void Nix::add(int a, QString b) { d->myMap[a] = b; }

似乎称为移动分配运算符:

QSharedDataPointer<T> &QSharedDataPointer::operator=(QSharedDataPointer<T> &&other)

如果文档正确,我需要另一个文档:

QSharedDataPointer<T> &QSharedDataPointer::operator=(const QSharedDataPointer<T> &o)

我试图使用铸造语句,但没有成功。

这只是用另一个指针代替指针。

nix1 = nix2

c++ qt segmentation-fault shared assignment-operator
1个回答
0
投票

{ Nix nix4(4, "Hello, I'm four"); *nix1 = nix4; } qWarning() << "nix1: " << nix1->display(4);

那起作用

溶解,实际上是在SGAIST(QT.Forum)的帮助下


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.