通过引用传递智能指针 [英] Passing smart-pointers by reference

查看:90
本文介绍了通过引用传递智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

智能指针通常很小,因此按值传递不是问题,但是将引用传递给它们有任何问题.还是在某些特定情况下不应该这样做?

Smart-pointers are generally tiny so passing by value isn't a problem, but is there any problem passing references to them; or rather are there specific cases where this mustn't be done?

我正在编写一个包装器库,我的几个类都将智能指针对象包装在基础库中...我的类不是智能指针,但API当前通过值传递智能指针对象.

I'm writing a wrapper library and several of my classes wrap smart-pointer objects in the underlying library... my classes are not smart-pointers but the APIs currently pass smart-pointer objects by value.

例如当前代码:

void class::method(const AnimalPtr pAnimal) { ... }

成为

void class::method(const MyAnimal &animal){...}

其中 MyAnimal 是我的新包装类,封装了 AnimalPtr .

where MyAnimal is my new wrapper class encapsulating AnimalPtr.

不能保证Wrapper类有一天不会超出包装智能指针的范围,因此按值传递使我感到紧张.

There is no guarantee the Wrapper classes won't one day grow beyond wrapping a smart-pointer, so passing by value makes me nervous.

推荐答案

在大多数情况下,您应该通过引用而不是值传递共享指针.尽管 std :: shared_ptr 的大小很小,但是复制的成本涉及到原子操作(概念上,原子的增量和原子的减损导致了副本的复制,尽管我相信某些实现能够进行非原子增量).

You should pass shared pointers by reference, not value, in most cases. While the size of a std::shared_ptr is small, the cost of copying involves an atomic operation (conceptually an atomic increment and an atomic decrement on destruction of the copy, although I believe that some implementations manage to do a non-atomic increment).

在其他情况下,例如 std :: unique_ptr ,您可能更喜欢按值传递,因为 copy 必须是一个动作,并且显然文档,该对象的所有权已转让给函数(如果您不想转让所有权,则将引用传递给真实对象,而不是 std :: unique_ptr ).

In other cases, for example std::unique_ptr you might prefer to pass by value, as the copy will have to be a move and it clearly documents that ownership of the object is transferred to the function (if you don't want to transfer ownership, then pass a reference to the real object, not the std::unique_ptr).

在其他情况下,您的里程可能会有所不同.您需要知道复制对于智能指针的含义,以及是否需要支付费用.

In other cases your mileage might vary. You need to be aware of what the semantics of copy are for your smart pointer, and whether you need to pay for the cost or not.

这篇关于通过引用传递智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆