c++ - 将 unique_ptr 传递给函数后如何使用它?

标签 c++ unique-ptr

我刚开始学习新的 C++ 内存模型:

#include <string>
#include <iostream>
#include <memory>

void print(unique_ptr<std::string> s) {
        std::cout << *s << " " <<  s->size() << "\n";
}

int main() {
        auto s = std::make_unique<std::string>("Hello");
        print(std::move(s));
        std::cout << *s;
        return 0;
}

现在调用 cout << *s;应该会导致段错误。我明白为什么会这样。但我也想知道是否有办法取回所有权。我希望能够在将值传递给函数后使用它。

最佳答案

如果您不想转移所拥有对象的所有权,则不要将 unique_ptr 传递给该函数。相反,将引用或原始指针传递给函数(在现代 C++ 风格中,原始指针通常被理解为非拥有)。在您只想读取对象的情况下,const 引用通常是合适的:

void print(const std::string&);
// ...
print(*s);

关于c++ - 将 unique_ptr 传递给函数后如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56068295/

相关文章:

c++ - 为什么我的 CFRunLoopTimer 没有触发?

c++ - 当 std::lock_guard 仍在范围内时,使用 pthread_create 创建线程是否安全?

c++ - 为什么在 shared_ptr 只取一个时 unique_ptr 取两个模板参数?

c++ - 为什么我不能 std::move std::unique_ptrs between std::sets?

c++ - 在 C++ 中,如何创建从 T 到 T* 的转换?

c++ - 我想在使用 istream 运算符读取输入后使用 cin

c++ - 动态库、依赖和分布?

c++ - 使用 C++ 继承来增强具有所有权语义的类

c++ - 警告:在std::unique_ptr的声明中忽略模板参数上的属性(-Wignored-attributes)

c++ - 这是 unique_ptr 的正确用法吗?