2017-02-23 17 views
0

私はC++を初めて使用しています。誰かが私には、次のコードセグメントと間違っているものを教えてくださいすることができます -C++ newbie: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を使用しようとしていました。 012-> dump()は、セグメンテーション違反を引き起こします。しかし、私は「ダル」の代わりに文字列リテラルの「namestr」変数を使用するならば、V->(ダンプ)が正しく動作するように見える、次、すなわち -

std::shared_ptr<Person> r1(std::make_shared<Person>(namestr)); 

また、以下の方法もいるようです私はインターナイザーで文字列リテラルを使用していても動作します。

std::shared_ptr<Person> r1(new Person("Dull")); 

私が作っている間違いの指針は大変ありがとう!

+0

すぐにスコープ外に行ってきました一時的な文字列を作成したので

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

}; 

これは、寿命が保証されていない文字列への参照を格納しています。あなたは「鈍い」は申し訳ありませんがそれは「PLIST」を読んだことがあるはずです

+0

なぜあなたは 'const'を削除しましたか? –

+0

お返事ありがとうございました。それは意味をなさない。私が疑問に思っていたのは、なぜ次のフォームが*働くように見えるのかということでした。std :: shared_ptr r1(新しいPerson( "Dull")); –

+0

まだ消えたものにアクセスしようとしていないためです。その行は 'std :: string(" Dull ")'が実行されている間に参照が作成できます。行が実行された後、 "dull"が消えるので、ref( 'name')は無効です。その参照を使用しようとすると状況が悪くなる – pm100