如何传递std :: unique_ptr? [英] How to pass std::unique_ptr around?
问题描述
我第一次尝试使用C ++ 11 unique_ptr
;我正在替换我的一个项目中的多态原始指针,该项目属于一个类,但是经常通过。
I am having my first attempt at using C++11 unique_ptr
; I am replacing a polymorphic raw pointer inside a project of mine, which is owned by one class, but passed around quite frequently.
我曾经有以下功能:
I used to have functions like:
bool func(BaseClass* ptr, int other_arg) {
bool val;
// plain ordinary function that does something...
return val;
}
但是我很快意识到我将无法切换到: / p>
But I soon realized that I wouldn't be able to switch to:
bool func(std::unique_ptr<BaseClass> ptr, int other_arg);
因为调用者必须处理该函数的指针所有权,所以我不想。那么,解决我的问题的最佳方法是什么?
Because the caller would have to handle the pointer ownership to the function, what I don't want to. So, what is the best solution to my problem?
我虽然将指针作为参考传递,例如:
I though of passing the pointer as reference, like this:
bool func(const std::unique_ptr<BaseClass>& ptr, int other_arg);
但是我这样做非常不自在,首先是因为通过本来就是已经输入的东西似乎不是本能。 _ptr
作为参考,这将是参考的参考。其次,因为功能签名变得更大。第三,因为在生成的代码中,需要两个连续的指针间接访问才能到达我的变量。
But I feel very uncomfortable in doing so, firstly because it seems non instinctive to pass something already typed as _ptr
as reference, what would be a reference of a reference. Secondly because the function signature gets even bigger. Thirdly, because in the generated code, it would be necessary two consecutive pointer indirections to reach my variable.
推荐答案
函数使用pointee,传递对它的引用。没有理由将函数仅与某种智能指针配合使用:
If you want the function to use the pointee, pass a reference to it. There's no reason to tie the function to work only with some kind of smart pointer:
bool func(BaseClass& base, int other_arg);
在呼叫站点使用 operator *
:
func(*some_unique_ptr, 42);
或者,如果允许 base
自变量为null,请保持签名不变,并使用 get()
成员函数:
Alternatively, if the base
argument is allowed to be null, keep the signature as is, and use the get()
member function:
bool func(BaseClass* base, int other_arg);
func(some_unique_ptr.get(), 42);
这篇关于如何传递std :: unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!