用相同的 unique_ptr 做两次 std::move
Doing std::move twice with the same unique_ptr
如果我用相同的 unique_ptr 两次调用 std::move 会发生什么?
unique_ptr<int> foo(new int(5));
unique_ptr<int> bar = move(foo);
unique_ptr<int> baz = move(foo);
PS:不,std::unique_ptr usage 不是同一个问题。两个问题都是关于unique_ptr,这是它们之间唯一的共同点
从 unique_ptr
移动后,它会保留为 null。所以 baz
最终也会为空。
基本上没有。标准库要求移动库类型使其处于有效但未指定的状态。通过有效,它们意味着您仍然可以对不需要先决条件的对象执行操作。那就是为它分配一个新值或销毁它。对于 unique_ptr
我们实际上得到了更多的状态保证作为 move constructor guarantees that the moved from object is set to nullptr
。这意味着最终 bar
持有指针并且 foo
和 baz
都是 nullptr
.
如果我用相同的 unique_ptr 两次调用 std::move 会发生什么?
unique_ptr<int> foo(new int(5));
unique_ptr<int> bar = move(foo);
unique_ptr<int> baz = move(foo);
PS:不,std::unique_ptr usage 不是同一个问题。两个问题都是关于unique_ptr,这是它们之间唯一的共同点
从 unique_ptr
移动后,它会保留为 null。所以 baz
最终也会为空。
基本上没有。标准库要求移动库类型使其处于有效但未指定的状态。通过有效,它们意味着您仍然可以对不需要先决条件的对象执行操作。那就是为它分配一个新值或销毁它。对于 unique_ptr
我们实际上得到了更多的状态保证作为 move constructor guarantees that the moved from object is set to nullptr
。这意味着最终 bar
持有指针并且 foo
和 baz
都是 nullptr
.