我什么时候应该使用原始指针而不是智能指针?

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);
}

这篇关于我什么时候应该使用原始指针而不是智能指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)