Search code examples
c++shared-ptrmake-shared

C++ newbie: Operation of make_shared


I am new to 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.

v->dump() causes a segmentation fault. However, if I use the 'namestr' variable instead of the string literal "Dull" then the v->dump() appears to work correctly, i.e. the following -

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!


Solution

  • 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