我是C++新手。有人可以請讓我知道什麼是錯用下面的代碼段 -C++新手:make_shared的操作
class Person {
public:
const std::string& name;
Person(const std::string& s): name(s) {}
void dump(void) const {
cout << name << endl;
//cout << &name << endl;
}
};
std::map<std::string, std::shared_ptr<Person>> plist;
std::string namestr = "Hoo";
std::shared_ptr<Person> r1(std::make_shared<Person>("Dull"));
plist.insert({"Key1", r1});
auto u = plist.find("Key1");
shared_ptr<Person> v = u->second;
v->dump();
plist.erase(plist.find("Key1"));
我的目的是創建一個Person對象的數據庫,我試圖用的shared_ptr了點。
v-> dump()導致分段錯誤。不過,如果我使用「nameStr的」變量而不是字符串「平淡」,那麼的V->轉儲()似乎正常工作,即以下 -
std::shared_ptr<Person> r1(std::make_shared<Person>(namestr));
此外,下面的方法也似乎即使我在初始化器中使用了字符串文字,也是如此。
std::shared_ptr<Person> r1(new Person("Dull"));
指出我犯的錯誤將不勝感激!
對不起應該已經閱讀「的plist」臨時串
你的代碼失敗。我會糾正原來的帖子。 –