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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With