具有共享指针的分段错误

时间:2019-03-24 14:38:18

标签: c++ segmentation-fault

此代码有什么问题(我将整个代码最小化了)?我不知道为什么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;
}

1 个答案:

答案 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);
    }