Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing const unique_ptr reference as parameter

 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.

like image 813
code Avatar asked Mar 07 '23 21:03

code


1 Answers

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.

like image 69
amc176 Avatar answered Mar 16 '23 12:03

amc176