gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:56:47 28 4
gpt4 key购买 nike

我正在测试 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 相同的对象,你删除对象然后尝试调用它的方法(删除后)

关于c++ - 访问持有 QString 的 shared_ptr 时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42113992/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com