简体   繁体   English

C ++新手:make_shared的操作

[英]C++ newbie: Operation of make_shared

I am new to C++. 我是C ++的新手。 Can someone please let me know what is wrong with the following code segment - 有人可以让我知道以下代码段有什么问题吗-

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

My intention is to create a database of Person objects and I was trying to use shared_ptr for that. 我的意图是创建一个Person对象的数据库,而我试图为此使用shared_ptr。

v->dump() causes a segmentation fault. v-> dump()导致分段错误。 However, if I use the 'namestr' variable instead of the string literal "Dull" then the v->dump() appears to work correctly, ie the following - 但是,如果我使用“ namestr”变量而不是字符串文字“ Dull”,则v-> dump()似乎可以正常工作,即以下代码-

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

Also, the following way also seems to work even though I use a string literal in the intializer. 此外,即使我在初始化器中使用了字符串文字,以下方法似乎也可以工作。

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

Pointers to the mistake I am making would be much appreciated! 指出我犯的错误的指针将不胜感激!

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

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

};

this is storing a reference to a string whose life time is not guaranteed. 这将存储对寿命无法保证的字符串的引用。 You should do 你应该做

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

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

};

You code fails because "Dull" created a temporary string that went out of scope immediately 您的代码失败,因为“ Dull”创建了一个临时字符串,该字符串立即超出范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM