问题描述
阅读后这个答案,看起来最好使用 智能指针 尽可能多,并将普通"/原始指针的使用减少到最低限度.
After reading this answer, it looks like it is a best practice to use smart pointers as much as possible, and to reduce the usage of "normal"/raw pointers to minimum.
这是真的吗?
推荐答案
不,这不是真的.如果一个函数需要一个指针并且与所有权无关,那么我强烈认为应该传递一个常规指针,原因如下:
No, it's not true. If a function needs a pointer and has nothing to do with ownership, then I strongly believe that a regular pointer should be passed for the following reasons:
- 没有所有权,因此您不知道要传递什么样的智能指针
- 如果你传递一个特定的指针,比如
shared_ptr
,那么你将无法传递,比如,scoped_ptr
- No ownership, therefore you don't know what kind of a smart pointer to pass
- If you pass a specific pointer, like
shared_ptr
, then you won't be able to pass, say,scoped_ptr
规则是这样的——如果你知道一个实体必须拥有对象的某种所有权,总是使用智能指针——它给你您需要的所有权类型.如果没有所有权的概念,从不使用智能指针.
The rule would be this - if you know that an entity must take a certain kind of ownership of the object, always use smart pointers - the one that gives you the kind of ownership you need. If there is no notion of ownership, never use smart pointers.
示例 1:
void PrintObject(shared_ptr<const Object> po) //bad
{
if(po)
po->Print();
else
log_error();
}
void PrintObject(const Object* po) //good
{
if(po)
po->Print();
else
log_error();
}
示例 2:
Object* createObject() //bad
{
return new Object;
}
some_smart_ptr<Object> createObject() //good
{
return some_smart_ptr<Object>(new Object);
}
这篇关于我什么时候应该使用原始指针而不是智能指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!