c++ - 保留 `unique_ptr` 未设置,直到我准备好分配它 : Is this how I re-assign it?

标签 c++ c++11

这个例子是在 iOS 的上下文中,但原则适用于其他地方......

// global variable... 
std::unique_ptr<Foo> global_foo_handle; 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // use Obj-C to compute a valid path string
    const char * path = [[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithUTF8String: "file.txt"]] UTF8String];
    // Only now can I call the ctor of my foo. 
    global_foo_handle = std::move(std::unique_ptr<Foo>(new Foo(path)));
}

这对我来说真的看起来不是那么理智。没有更清洁的方法吗?我看到唯一有效的 unique_ptr operator = 是移动分配。我想很清楚这里正在做什么。似乎我也可以省略 std::move,只要为新分配的 Foo 制作的临时 unique_ptr 仍然是临时的,而不是被制成左值。

我想我有点想知道为什么没有一个 operator= 接受指向 T 的指针?这样我们就跳过了临时 unique_ptr 的创建。

最佳答案

你不需要 std::move...

global_foo_handle = std::unique_ptr<Foo>(new Foo(path));

或者您可以重置值...

global_foo_handle.reset(new Foo(path));

但是,您必须了解删除器是 unique_ptr 类型的一部分,任何通过reset 分配给 unique_ptr 的指针都将被原始 unique_ptr 对象的删除器删除。

关于c++ - 保留 `unique_ptr` 未设置,直到我准备好分配它 : Is this how I re-assign it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22740608/

相关文章:

c++ - 如何创建 std::array 包装器类

c++ - 读取文件十六进制数据并存储到 C++ 中的字符串二维数组中

c++ - 为什么当我在 Ubuntu 终端上发送 SIGTERM (Ctrl + C) 时我的 C++ 代码没有终止?

c++ - 锁、互斥和临界区之间的区别

c++ - 将 std::unique_ptr 与 std::istream 一起使用?

c++ - 如何为包装需要 2 个参数的 c 函数的 unique_ptr 类成员创建自定义删除器?

c++ - 为什么按值传递和按右值传递重载 C++ 函数调用不明确?

c++ - 防弹 C++ 临时生命周期?

c++ - 使用 Eigen header 的模板函数

c++ - C++11 中的 lambda 表达式是什么?