void f1(unique_ptr<A[]>& upA){
//some work...
//callee can mess up smart pointer many ways for caller
upA.reset();
//some work...
}
void f2(const unique_ptr<A[]>& upA){
//some work...
//compiler stops callee from ruining smart pointer many ways for caller
upA.reset();
//some work...
}
f1(upAArray);
f2(upAArray);
In the above code, calling f1 is dangerous because the callee can mess up the smart pointer by resetting it, releasing it, etc. Calling f2 is safe and everything works great. If callee tries to do something bad, compiler catches it. This way, smart pointer is sound when call stack unwinds and we get back to the caller.
IMPORTANT, I'm not asking how best to pass smart pointers (i realize a regular raw pointer void f3(A* pAArray){} would be fine. I'm asking what is wrong with f2? The generall advice is to not use const ref to unique_ptr as parameter, while I see why this isn't optimal, I don't see why it is worse than f1().
In short, specifically, what is the rationale against f2()? Does it do something bad? It seems safe and sound (though certainly not optimal), I don't see why it is so bad.
One of the drawbacks about passing smart pointers by const reference (or a raw reference) is that the callee depends on implementation details of the caller. Code that doesn't interact with ownership should not be dependant on smart pointers, as their only purpose is modelling ownership.
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