Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Peet Whittaker Avatar asked Sep 07 '16 13:09

Peet Whittaker


2 Answers

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.

like image 113
Hatted Rooster Avatar answered Oct 17 '22 07:10

Hatted Rooster


The downsides are like with any const member: That the assignment and move-assignment operators don't work right (they would require you to overwrite _child) and that moving from the parent would not steal the _child (performance bug). Also it is uncommon to write code like this, possibly confusing people.

The gain is marginal because _child is private and therefore can only be accessed from inside the Parent, so the amount of code that can break invariants revolving around changing _child is limited to member functions and friends which need to be able to maintain invariants anyways.

I cannot imagine a situation where the gain would outweigh the downsides, but if you do you can certainly do it your way without breakage of other parts of the program.

like image 26
nwp Avatar answered Oct 17 '22 08:10

nwp