简体   繁体   English

将std :: unique_ptr传递给构造函数以获取所有权

[英]Passing std::unique_ptr to constructor to take ownership

I want to pass a std::unique_ptr to the constructor of a class that will take ownership of the data owned by the std::unique_ptr . 我想将std::unique_ptr传递给一个类的构造函数,该类将获取std::unique_ptr拥有的数据的所有权。

Are there any differences between the approaches foo and bar below in terms of how the compiler handles them that would make one of them preferable? 下面的方法foobar在编译器处理它们的方式方面是否有任何区别,从而使其中一种更可取?

foo class: foo类:

template <class T>
class foo
{
    std::unique_ptr<T> data_;

public:
    foo(std::unique_ptr<T>&& data) :
        data_{ std::forward<std::unique_ptr<T>>(data) }
    {
    }
};

bar class: bar班:

template <class T>
class bar
{
    std::unique_ptr<T> data_;

public:
    bar(std::unique_ptr<T> data) :
        data_{ std::move(data) }
    {
    }
};

Binding to a reference requires one less move: 绑定到引用只需少走一走:

void f(std::unique_ptr<T>&& p) { g(std::move(p)); }

f(std::make_unique<T>());  // no move, g binds directly to the temporary

Binding to an object parameter requires one actual move: 绑定到对象参数需要一个实际步骤:

void f(std::unique_ptr<T> p) { g(std::move(p)); }

f(std::make_unique<T>());  // p constructed (= moved) from temporary,
                           // g binds to p

The extra move involves one pointer copy, one setting of a pointer to null, and one destructor with a condition check. 额外的动作包括一个指针副本,一个指向null的指针的设置以及一个带有条件检查的析构函数。 This is not a big cost, and the question of which style to use depends on the kind of code you're writing: 这并不是很大的代价,使用哪种样式的问题取决于您编写的代码类型:

The more leaf your code is and the less it is used, the more the simple version with by-value passing buys you simplicity. 您的代码叶子越多,使用的代码就越少,带有按值传递的简单版本越能使您变得简单。 Conversely, the more library your code is and the less you know your users, the more there is value in not imposing avoidable cost, no matter how small. 相反,代码的库越多,对用户的了解就越少,无论施加多小的开销,其所具有的价值都不会增加。

You decide. 你决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM