Peet Whittaker Peet Whittaker - 1 year ago 93
C++ Question

Marking std::unique_ptr class member as const

A lot of the examples for using

to manage ownership of class dependencies look like the following:

class Parent
Parent(Child&& child) :
std::unique_ptr<Child> _child;

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download