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

16

在声明了一个 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的理解极为不足...

1个回答

32

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

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

您可以重置它,用新的资源(在您的情况下没有实际删除发生)替换已管理的资源。

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)};

1
另一种方法是使用swap而不是operator= - jxh
非常好,谢谢!现在先使用第一种方法,更改编译器设置后我会尝试C++14版本。(虽然还不能接受答案...) - Kvothe
1
@Kvothe 如果你四处看看,就能找到使用make_unique的动机,几乎不用写new是相当酷的。 - Ryan Haining
1
尝试使用此答案来实现make_unique - jxh
为什么 auto result = std::unique_ptr<std::string> {std::string {}}; 不能工作? - jrwren
@jrwren 这个问题是如何修改现有的 unique_ptr。您的建议缺少一个 new,但是在创建新的 unique_ptr 方面是有效的,尽管我会更倾向于使用 auto result = std::make_unique<std::string>(); 这样您就不必重复类型了。 - Ryan Haining

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接