Passing const unique_ptr reference as parameter

China☆狼群 提交于 2020-01-04 05:51:09

问题


 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.


回答1:


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.



来源:https://stackoverflow.com/questions/48811917/passing-const-unique-ptr-reference-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!