How unique_ptr Parameters Should Be Handled in Constructors and Functions
Scenario
Consider a class Base referencing itself as follows:
class Base { public: typedef unique_ptr<Base> UPtr; Base() {} Base(Base::UPtr n) : next(std::move(n)) {} virtual ~Base() {} void setNext(Base::UPtr n) { next = std::move(n); } protected: Base::UPtr next; };
Methods to Pass unique_ptr Arguments
To use unique_ptr parameters effectively, consider the following methods:
1. By Value (A)
Base(std::unique_ptr<Base> n) : next(std::move(n)) {}
When called as Base newBase(std::move(nextBase));, this method transfers ownership of the pointer to the function. After construction, nextBase becomes empty.
2. By non-const l-value Reference (B)
Base(std::unique_ptr<Base> &n) : next(std::move(n)) {}
This requires an actual l-value (named variable) and allows the function to potentially claim ownership of the pointer.
3. By const l-value Reference (C)
Base(std::unique_ptr<Base> const &n);
This prevents the function from storing the pointer, but guarantees access to the object for the duration of its execution.
4. By r-value Reference (D)
Base(std::unique_ptr<Base> &&n) : next(std::move(n)) {}
Similar to (B), but requires the use of std::move when passing non-temporary arguments. The function may or may not claim ownership.
Recommendations
Manipulating unique_ptr
To move a unique_ptr, use std::move. This avoids copying and ensures proper transfer of ownership.
The above is the detailed content of How Should `unique_ptr` Parameters Be Passed in C Constructors and Functions?. For more information, please follow other related articles on the PHP Chinese website!