Search code examples
c++c++11unique-ptrstdstring

Should I use unique_ptr for a string?


I'm new to C++. I've heard that using unique_ptr / shared_ptr is the "way to go" for references to data allocated on the heap. Does it make sense, therefore, to use unique_ptrs instead of std::strings?


Solution

  • Why would you want to do that?

    An std::string object manages the life time of the "contained" string (memory bytes) by itself.

    Since you are new to C++. Inside your function / class method, I will advice you create your objects on the stack: Like so:

      std::string s;
    

    as opposed to using the heap:

     std::string* s = new std::string();
    

    Objects created on the stack will be destroyed when your object goes out of scope. So there is no need for smart pointers.

    You can following this link to know more: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/