如何将字符串的值分配给 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
)?我尝试过的方法都不起作用.
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
其中 another_str_var
是之前声明和分配的 std::string
.
where another_str_var
is an std::string
that is declared and assigned earlier.
很明显,我对 std::unique_ptr
正在做的事情的理解严重不足......
Clearly my understanding of what std::unique_ptr
is doing is woefully inadequate...
推荐答案
你可以使用 std::make_unique
在 C++14 中创建和移动赋值而无需显式 new
或必须重复类型名称 std::字符串
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));
您可以创建一个新的 unique_ptr
并将其分配到您的原始文件中,尽管这总是让我觉得很凌乱.
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)};
这篇关于如何将字符串的值分配给 std::unique_ptr<std::string>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!