Passing std :: unique_ptr to the constructor to get ownership

I want to pass std::unique_ptr constructor of the class that will own the data belonging to std::unique_ptr .

Are there any differences between the foo and bar approaches below in terms of how the compiler processes them, which would make one of them preferable?

foo class:

 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:

 template <class T> class bar { std::unique_ptr<T> data_; public: bar(std::unique_ptr<T> data) : data_{ std::move(data) } { } }; 
+5
source share
1 answer

Binding to a link requires one smaller 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 

An additional move includes one copy of the pointer, one setting of the pointer to zero, and one destructor with state checking. It's not a big cost, and the question of which style to use depends on the type of code you write:

The larger your code and the less it is used, the more simple the buy-in version gives you simplicity. Conversely, the more the library has your code and the less you know your users, the greater the value is not to impose an inevitable cost, no matter how small.

You decide.

+5
source

Source: https://habr.com/ru/post/1266369/


All Articles