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

Program crashing when accessing shared_ptr holding 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,所以在分配引用计数器应该增加之后。

提前致谢

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