C ++ - 指针传递问题 [英] C++ - pointer passing question

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

问题描述

有人有任何想法如何传递 boost :: shared_ptr - 按值或引用。



在我的平台(32位) sizeof(shared_ptr)等于8个字节,它看起来像我应该通过引用,但也许有人有另一个意见/

解决方案

您可以通过以下两种方式看到这些:




  • a boost :: shared_ptr 是一个对象(应该由const和amp传递)。


  • a boost :: shared_ptr 建模指针,应视为指针。




这两个选项都有效,第二个选项会产生构建和销毁附加实例的费用除非你编写性能关键代码,否则这是一个大问题。)



有两种情况,你应该传递值:


  • 也就是说,如果您考虑在未来的某个地方用 T * 替换 shared_ptr< T> 有意义的是写 typedef shared_ptr< T> TPtr; 并将您的函数定义为 void yourfunction(TPtr value)



    case,当你更改指针类型时,你只需要修改 typedef 行。


  • 您在两个具有不同生命周期的模块之间共享指针。在这种情况下,您需要确保您有两个智能指针实例,并且都增加指针的引用计数。




在其他情况下,这是一个偏好问题(除非你编写性能关键代码,在这种情况下适用不同的规则)。


Does somebody have any idead on how to pass boost::shared_ptr - by value or by reference.

On my platform (32bit) sizeof(shared_ptr) equals 8 bytes and it looks like I should pass them by reference, but maybe somebody has another opinion / did a profile / something like that?

解决方案

You can see this in two ways:

  • a boost::shared_ptr is an object (and should be passed by const &).

  • a boost::shared_ptr models a pointer and should be treated as a pointer.

Both of them are valid, and the second option will incur the cost of constructing and destructing the additional instance (which shouldn't be a big issue unless you're writing performance-critical code).

There are two cases when you should pass by value:

  • when you're not sure that the type of the pointer will remain the same. That is, if you are considering replacing the shared_ptr<T> with T* in your codebase somewhere in the future, it makes sense to write typedef shared_ptr<T> TPtr; and define your functions as void yourfunction(TPtr value)

    In this case, when you change the pointer type you will only have to modify the typedef line.

  • when you are sharing a pointer between two modules with a different lifetime. In that case, you need to make sure you have two instances of the smart pointer, and that both increment the reference count of the pointer.

In other cases, it's a matter of preference (unless you're writing performance-critical code in which case different rules apply).

这篇关于C ++ - 指针传递问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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