Returning unique_ptr and preventing move
-
I have a class that has a property of type
std::unique_ptr
. I am implementing the gets and sets methods of this class and I need that the unique_ptr that is returned by the get method cannot be moved, ie that the pointer cannot be moved withstd::move
.
How does this return have to be to guarantee this?class Operator { private: QString _name; QString _login; QString _passw; std::unique_ptr<Profile> _profile; public: Operator(); Operator(const QString &name, const QString &login, const QString &passw, std::unique_ptr<Profile> getProfile); QString getName() const; void setName(const QString &name); QString getLogin() const; void setLogin(const QString &login); QString getPassw() const; void setPassw(const QString &passw); std::unique_ptr<Profile> getProfile() const; //Should I return by reference, by value, by lvalue (&), rvalue (&&)? void setProfile(std::unique_ptr<Profile> profile); };
-
@Exotic_Devel said in Returning unique_ptr and preventing move:
Profile * getProfile() const;
Is simplest. The owned object continues to live where it does, you just return the member. If you can be sure that
Profile
is always valid, you can even returnProfile &
. -
It looks like you can return smart pointers via RVO, but it might require C++17:
https://www.internalpointers.com/post/move-smart-pointers-and-out-functions-modern-cThe comments also mention using std::move(ptr) to return a smart pointer, but you seemed to indicate problems with that.
-
@fcarney said in Returning unique_ptr and preventing move:
The comments also mention using std::move(ptr) to return a smart pointer, but you seemed to indicate problems with that.
The typical problem being that returning the
unique_ptr
transfers ownership. -
@kshegunov said in Returning unique_ptr and preventing move:
The typical problem being that returning the unique_ptr transfers ownership.
I am confused then. I thought he had trouble doing this. I didnt understand that he didnt want it to move.