是否对接口(interface)进行了修改,可以使第二次调用起作用?
还是我应该保持原样?
我怀疑第一个案例中的额外结构是故意设计的,因此很明显所有权正在转移。
#include <memory>
struct Bar { };
typedef std::unique_ptr<Bar> UPBar;
void foo1( UPBar p ) { }
void foo2( UPBar p ) { foo1( move( p )); }
void foo3( UPBar p ) { foo2( move( p )); }
void foo4( UPBar p ) { foo3( move( p )); }
int main(int argc, char** argv)
{
UPBar p( new Bar );
foo4( move( p )); // ok, but requires an extra construction vs line below
foo4( new Bar ); // fails: any modification to get this to work?
return 0;
}
第二个问题:如果我更改传递给 RValue-References (&&) 的所有参数,这样做有什么缺点吗?事实上,我应该确保我所有的 std::unique_ptr<>
参数通过 RValue-References 传递?
最佳答案
您可以将 unique_ptr
构造为临时值:
foo4( UPBar( new Bar ));
您还可以编写一个make_unique
函数模板,类似于shared_ptr
的make_shared
:
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<T>(args)...));
}
foo4( make_unique<Bar>() );
// other constructors are also callable:
foo4( make_unique<Bar>(x, y, z) );
关于c++ - std::unique_ptr 作为参数的正确复制语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8366181/