c++ - std::unique_ptr 作为参数的正确复制语义

标签 c++ c++11 smart-pointers

是否对接口(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_ptrmake_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/

相关文章:

c++ - 模板中的自动返回类型

c++ - For循环在C++中以字符串长度无限运行

c++ - 在 STL vector 中存储对象 - 最少的方法集

c++ - 结构填充

c++ - 在智能指针中安全地包含任意数据

c++ - AtlComPtrAssign 需要什么?

c++ - 如何创建锁定和解锁互斥锁的智能指针?

c++ - 基类和派生类中同名的静态成员变量

c++ - 声明模板的共享指针

c++ - 在这种情况下,模板参数推导如何工作?