Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 544
Akira Kido Avatar asked Jan 03 '23 20:01

Akira Kido


1 Answers

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/

like image 65
Gamma.X Avatar answered Jan 15 '23 08:01

Gamma.X