16

After declaring an std::unique_ptr<std::string> but without assigning it (so it contains an std::nullptr to begin with) - how to assign a value to it (i.e. I no longer want it to be holding std::nullptr)? Neither of the methods I've attempted work.

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 an std::string that is declared and assigned earlier.

Clearly my understanding of what std::unique_ptr is doing is woefully inadequate...

Kvothe
  • 1,819
  • 2
  • 23
  • 37

1 Answers1

32

You could use std::make_unique in C++14 to create and move assign without the explicit new or having to repeat the type name std::string

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

You could reset it, which replaces the managed resources with a new one (in your case there's no actual deletion happening though).

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

You could create a new unique_ptr and move assign it into your original, though this always strikes me as messy.

my_str_ptr = std::unique_ptr<std::string>{new std::string(another_str_var)};
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • 1
    One more is to use `swap` instead of `operator=`. – jxh May 01 '15 at 18:34
  • Excellent, thank you! Making use of the first method for now, I'll try out the C++14 version after changing my compiler settings. (Can't accept the answer yet though...) – Kvothe May 01 '15 at 18:37
  • 1
    @Kvothe If you look around you can find the motivation for using `make_unique`, being able to almost never write `new` is pretty cool. – Ryan Haining May 01 '15 at 18:46
  • 1
    Try [this answer](http://stackoverflow.com/a/13512344/315052) for an implementation of `make_unique`. – jxh May 01 '15 at 18:47
  • Why doesn't `auto result = std::unique_ptr {std::string {}};` work? – jrwren May 07 '19 at 19:08
  • @jrwren this question is how to modify an existing `unique_ptr`. Your suggestion is missing a `new`, but is otherwise a valid way to create a new `unique_ptr`, though I'd say favor `auto result = std::make_unique();` so you don't have to repeat the type. – Ryan Haining May 07 '19 at 22:55