Peet Whittaker Peet Whittaker - 2 months ago 18
C++ Question

Marking std::unique_ptr class member as const

A lot of the examples for using

std::unique_ptr
to manage ownership of class dependencies look like the following:

class Parent
{
public:
Parent(Child&& child) :
_child(std::make_unique<Child>(std::move(child))){}
private:
std::unique_ptr<Child> _child;
};


My question is whether marking the
_child
member as
const
have any unexpected side effects? (Aside from being ensuring that
reset()
,
release()
etc. cannot be called on
_child
).

I ask since I have not yet seen it in an example and don't whether that is intentional or just for brevity/generality.

Answer

Because of the nature of a std::unique_ptr(sole ownership of an object) it's required to have no copy constructor whatsoever. The move constructor(6) only takes non-const rvalue-references which means that if you'd try to make your _child const and move it you'd get a nice compilation error :)

Even if a custom unique_ptr would take a const rvalue-reference it would be impossible to implement.