如何将字符串的值赋给 std::unique_ptr<std::string>?

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

在声明一个 std::unique_ptr<std::string> 但没有分配它之后(因此它包含一个 std::nullptr 开始) - 如何为其分配一个值(即我不再希望它持有 std::nullptr)?我尝试过的两种方法都不起作用。

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

其中 another_str_var 是之前声明和分配的 std::string

很明显,我对 std::unique_ptr 所做的事情的理解严重不足...

您可以在 C++14 中使用 std::make_unique 来创建和移动赋值,而无需显式 new 或不必重复类型名称 std::string

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

你可以 reset 它,它用新的资源替换托管资源(在你的情况下没有实际删除发生)。

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

您可以创建一个新的 unique_ptr 并将其分配到您的原始文件中,尽管这总是让我觉得很乱。

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