How to assign a value of a string to a std::unique_ptr?

前端 未结 1 1320
执笔经年
执笔经年 2021-02-19 23:40

After declaring an std::unique_ptr but without assigning it (so it contains an std::nullptr to begin with) - how to assign a value t

1条回答
  •  温柔的废话
    2021-02-20 00:11

    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(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{new std::string(another_str_var)};
    

    0 讨论(0)
提交回复
热议问题