C ++ - 指针传递问题 [英] C++ - pointer passing question
问题描述
有人有任何想法如何传递 boost :: shared_ptr
- 按值或引用。
在我的平台(32位) sizeof(shared_ptr)
等于8个字节,它看起来像我应该通过引用,但也许有人有另一个意见/
您可以通过以下两种方式看到这些:
-
a
boost :: shared_ptr
是一个对象(应该由const和amp传递)。 -
a
boost :: shared_ptr
建模指针,应视为指针。
这两个选项都有效,第二个选项会产生构建和销毁附加实例的费用除非你编写性能关键代码,否则这是一个大问题。)
有两种情况,你应该传递值:当您不确定指针的类型是否保持不变时,p>
-
也就是说,如果您考虑在未来的某个地方用
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>
withT*
in your codebase somewhere in the future, it makes sense to writetypedef shared_ptr<T> TPtr;
and define your functions asvoid 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屋!