在声明了一个 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
的理解极为不足...
swap
而不是operator=
。 - jxhmake_unique
的动机,几乎不用写new
是相当酷的。 - Ryan Hainingmake_unique
。 - jxhauto result = std::unique_ptr<std::string> {std::string {}};
不能工作? - jrwrenunique_ptr
。您的建议缺少一个new
,但是在创建新的unique_ptr
方面是有效的,尽管我会更倾向于使用auto result = std::make_unique<std::string>();
这样您就不必重复类型了。 - Ryan Haining