【问题标题】:How to assign a value of a string to a std::unique_ptr<std::string>?如何将字符串的值分配给 std::unique_ptr<std::string>?
【发布时间】:2015-07-11 15:15:18
【问题描述】:

在声明 std::unique_ptr&lt;std::string&gt; 但没有分配它(因此它包含一个 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++ string unique-ptr


    【解决方案1】:

    您可以在 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)};
    

    【讨论】:

    • 还有一个是用swap代替operator=
    • 太好了,谢谢!现在使用第一种方法,我将在更改编译器设置后尝试 C++14 版本。 (虽然还不能接受答案...)
    • @Kvothe 如果你环顾四周,你会发现使用make_unique 的动机,几乎从不写new 非常酷。
    • 尝试this answer 实现make_unique
    • 为什么auto result = std::unique_ptr&lt;std::string&gt; {std::string {}}; 不起作用?
    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2012-07-21
    • 2019-03-31
    • 1970-01-01
    相关资源
    最近更新 更多