ophilbinbriscoe ophilbinbriscoe - 1 year ago 45
C++ Question

Is this proper usage of a unique_ptr?

from what I've discerned by reading through most of the questions on here that pop up when looking up unique pointers, this seems to me like it should provide the behavior described by the Builder pattern.

I want any instance of Builder (or its sub-classes, since it doesn't implement any procedures for modifying the object under construction) to own the object under construction until Close returns the unique pointer to the caller, at which point the caller takes ownership.


template <class type> class Builder
unique_ptr<type> Close();
unique_ptr<type> _uptr;


template<class type> Builder<type>::Builder()
uptr = make_unique<type>();

template<class type> Builder<type>::~Builder()

template<class type> unique_ptr<type> Builder<type>::Close()
return uptr;

Do I understand the semantics of passing a unique pointer by value?

(includes and namespaces omitted for brevity / legibility)

Answer Source

std::unique_ptr cannot be copied. Instead, you will have to move uptr in order to properly transfer ownership of the underlying pointer.

template<class type> unique_ptr<type> Builder<type>::Close()
    return std::move(uptr);