C++新手:make_shared的操作

问题描述:

我是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")); 

指出我犯的错误将不胜感激!

+0

对不起应该已经阅读“的plist”临时串

class Person { public: const std::string name; Person(const std::string& s): name(s) {} void dump(void) const { cout << name << endl; //cout << &name << endl; } }; 

你的代码失败。我会纠正原来的帖子。 –

class Person { 
    public: 
     const std::string& name; 

     Person(const std::string& s): name(s) {} 
     void dump(void) const { 
     cout << name << endl; 
     //cout << &name << endl; 
     } 

}; 

这是存储对其生命时间不能保证的字符串的引用。你应该这样做,因为“沉闷”创建出去的范围内立即

+0

你为什么删除'const'? –

+0

非常感谢回复。这确实有道理。我想知道为什么下面的形式*似乎*工作 - std :: shared_ptr R1(新人(“愚蠢”)); –

+0

,因为您尚未尝试访问任何已消失的内容。当该行正在执行'std :: string(“Dull”)'时,您可以创建一个对它的引用。该行执行“无效”消失后,ref('name')无效。当你尝试使用这个参考 – pm100