How to assign string value to std :: unique_ptr <std :: string>?

std::unique_ptr<std::string> declaring std::unique_ptr<std::string> but not assigning it (so it contains std::nullptr ) - how to assign a value to it (i.e. I no longer want it to hold std::nullptr ) ? None of the methods I tried to execute.

 std::unique_ptr<std::string> my_str_ptr; my_str_ptr = new std::string(another_str_var); // compiler error *my_str_ptr = another_str_var; // runtime error 

where another_str_var is the std::string declared and assigned earlier.

Clearly, my understanding of what std::unique_ptr is extremely inadequate ...

+5
source share
1 answer

You can reset , which replaces managed resources with a new one (in your case, the actual deletion does not occur).

 my_str_ptr.reset(new std::string(another_str_var)); 

You can create a new unique_ptr and move it to your original, although it always seems dirty to me.

 my_str_ptr = std::unique_ptr<std::string>{new std::string(another_str_var)}; 

Or you can use std::make_unique in C ++ 14 to create and move an assignment without explicitly new or repeating a name like std::string

 my_str_ptr = std::make_unique<std::string>(another_str_var); 
+11
source

All Articles