Home >Backend Development >C++ >How Should I Pass Unique Pointers as Function or Constructor Arguments in C ?
Unique pointers (unique_ptr) uphold the principle of unique ownership in C 11. When dealing with unique pointers as function or constructor arguments, several options arise with distinct implications.
Base(std::unique_ptr<Base> n) : next(std::move(n)) {}
This method transfers ownership of the unique pointer to the function/object. The pointer's contents are moved into the function, leaving the original pointer empty after the operation.
Base(std::unique_ptr<Base> &n) : next(std::move(n)) {}
Allows the function to both access and potentially claim ownership of the unique pointer. However, this behavior is not guaranteed and requires inspection of the function's implementation to determine its handling of the pointer.
Base(std::unique_ptr<Base> const &n);
Prevents the function from claiming ownership of the unique pointer. The pointer can be accessed but not stored or modified.
Base(std::unique_ptr<Base> &&n) : next(std::move(n)) {}
Comparable to passing by non-const L-Value reference, but requires the use of std::move when passing non-temporary arguments. ownership may or may not be claimed by the function, making it less predictable.
To move a unique pointer, use std::move. Copying a unique pointer is not allowed:
std::unique_ptr<Base> newPtr(std::move(oldPtr));
The above is the detailed content of How Should I Pass Unique Pointers as Function or Constructor Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!