[英]When using shared_ptr should I just use the shared_ptr declaration once or declare shared_ptr everywhere I pass it?
When using shared_ptr
, should I just use the shared_ptr
declaration once or declare shared_ptr
everywhere I pass it? 当使用
shared_ptr
,我应该只使用一次shared_ptr
声明,还是在传递它的地方声明shared_ptr
?
So in the function where I new up the instance I wrap it in a shared_ptr
but when I return it from the function I could also return a shared_ptr
or, using the get()
on the shared_ptr
, just return a normal pointer. 所以在功能,我新起来的情况下我将它包装在一个
shared_ptr
,但是当我从函数返回它我也可以返回一个shared_ptr
,或使用get()
在shared_ptr
,只返回一个正常的指针。
So my question is, should I just use shared_ptr<myType>
when I new the instance and then pass normal pointers around or should I be passing shared_ptr<myType>
everywhere? 所以我的问题是,我应该在新实例时使用
shared_ptr<myType>
然后传递普通指针,还是应该在所有地方传递shared_ptr<myType>
?
Creating a shared_ptr
doesn't imbue magical powers on its pointee object. 创建一个
shared_ptr
并不会给它的指针对象带来神奇的力量。 The magic is all in the shared_ptr
— and its copies — itself. 神奇的是所有在
shared_ptr
- 及其副本 - 本身。 If you stop using it, you lose your reference counting; 如果您停止使用它,则会丢失引用计数; worse, because you used it at some point , the object will be automatically deleted when you don't expect it.
更糟糕的是,因为您在某些时候使用它,所以当您不期望它时,该对象将被自动删除。
The whole point of having shared_ptr
is that you know your object won't get destroyed when you're still using it somewhere. 具有整点
shared_ptr
是,你知道,当你还在使用它的地方,你的对象将不会被破坏。
In the following: 在下面的:
T* foo() {
shared_ptr<T> sp(new T());
return sp.get();
// ^ the only shared_ptr<T> referencing the obj is dead;
// obj is deleted;
// returned pointer invalid before you can even do anything with it
}
your pointer is immediately invalid. 你的指针立即无效。
There may well be circumstances in which you extract a raw pointer, but these should be rare. 在某种情况下,您可能会提取原始指针,但这些应该很少见。 If you are in a function where you know you don't need the reference counting, then just pass the
shared_ptr
in by reference. 如果你是在你知道你不需要引用计数功能,那么就通过
shared_ptr
引用英寸
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.