2017-02-23 101 views
0

我是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; } }; 

你的代碼失敗。我會糾正原來的帖子。 –

回答

1
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