Kvo*_*the 10 c++ string unique-ptr
在声明一个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
Run Code Online (Sandbox Code Playgroud)
在哪里another_str_var是std::string先前声明和分配的.
很明显,我对std::unique_ptr正在做的事情的理解非常不足......
Rya*_*ing 22
您可以std::make_unique在C++ 14中使用创建和移动assign而不显式new或不必重复类型名称std::string
my_str_ptr = std::make_unique<std::string>(another_str_var);
Run Code Online (Sandbox Code Playgroud)
您可以重置它,用新的替换托管资源(在您的情况下,虽然没有发生实际的删除).
my_str_ptr.reset(new std::string(another_str_var));
Run Code Online (Sandbox Code Playgroud)
你可以创建一个新的unique_ptr并将其分配到你的原始版本中,尽管这总是让我觉得很乱.
my_str_ptr = std::unique_ptr<std::string>{new std::string(another_str_var)};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6672 次 |
| 最近记录: |