此代码有什么问题(我将整个代码最小化了)?我不知道为什么pu.useIt();
会导致细分错误。
#include <memory>
using namespace std;
class Person {
private:
shared_ptr<string> name;
public:
void setName(shared_ptr<string> name) {
this->name = name;
}
shared_ptr<string> getName() {
return name;
}
};
class PersonCreator {
shared_ptr<Person> person;
public:
void createAmy() {
shared_ptr<string> amysName = make_shared<string>("amy");
person->setName(amysName);
}
};
class PersonUser {
public:
void useIt() {
PersonCreator pc;
pc.createAmy();
}
};
int main()
{
PersonUser pu;
pu.useIt();
return 0;
}
答案 0 :(得分:2)
您需要初始化person
,现在它为空,shared_ptr的默认ctor表示它指向nullptr:
void createAmy() {
shared_ptr<string> amysName = make_shared<string>("amy");
person = std::make_shared<Person>(); // added
person->setName(amysName);
}