访问持有QString的shared_ptr时程序崩溃

时间:2017-02-08 13:05:52

标签: c++ qt pointers shared-ptr qstring

我正在测试shared_ptrs和QStrings,我遇到了一个我不完全理解的崩溃。这是代码:

#include <QCoreApplication>
#include <QString>

#include <iostream>

class Base {
 public:
  Base(const QString& str1, const QString& str2, const QString& str3) {
   member1_ = std::make_shared<Internal>();
   (*member1_).i1 = str1;
   (*member1_).i2 = str2;
   member2_ = std::make_shared<QString>(str3);
 }
 QString getMember() { return *member2_; }
 QString getInternalMember() { return (*member1_).i1; }
protected:
 Base(const Base&) = default;
 Base& operator=(const Base&) = default;
 Base(Base&&) = default;
 Base& operator=(Base&&) = default;

private:
 struct Internal {
  QString i1;
  QString i2;
 };
 std::shared_ptr<Internal> member1_;
 std::shared_ptr<QString> member2_;
};

class Derived : public Base {
 public:
  Derived(const QString& str1, const QString& str2, const QString& str3) : Base(str1, str2, str3) {
   derivedMember_ = 1;
  }
 private:
  int derivedMember_;
};

int main(int argc, char *argv[]) {
 QCoreApplication a(argc, argv);
 Derived* d1 = new Derived("param1", "param2", "param3");
 std::cout << "d1 created " << d1->getMember().toStdString() << "-" << d1->getInternalMember().toStdString() << std::endl;
 Derived* d2 = d1;
 delete d1;
 std::cout << "d2 created " << d2->getMember().toStdString() << "-" << d2->getInternalMember().toStdString() << std::endl;
 return a.exec();
}

为什么会崩溃?我正在使用shared_ptrs,因此在赋值后,引用计数器应该递增。

提前致谢

1 个答案:

答案 0 :(得分:3)

d2指向与d1相同的对象,删除对象然后尝试调用其方法(删除后)