When should I use raw pointers over smart pointers?(我什么时候应该使用原始指针而不是智能指针?)
问题描述
阅读后这个答案,看起来最好使用 智能指针 尽可能多,并将普通"/原始指针的使用减少到最低限度.
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);
}
这篇关于我什么时候应该使用原始指针而不是智能指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我什么时候应该使用原始指针而不是智能指针?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
