問題描述
閱讀后這個答案,看起來最好使用 智能指針 盡可能多,并將普通"/原始指針的使用減少到最低限度.
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.
這是真的嗎?
推薦答案
不,這不是真的.如果一個函數(shù)需要一個指針并且與所有權無關,那么我強烈認為應該傳遞一個常規(guī)指針,原因如下:
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
規(guī)則是這樣的——如果你知道一個實體必須擁有對象的某種所有權,總是使用智能指針——它給你您需要的所有權類型.如果沒有所有權的概念,從不使用智能指針.
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);
}
這篇關于我什么時候應該使用原始指針而不是智能指針?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!