When should I use raw pointers over smart pointers?

后端 未结 8 1414
礼貌的吻别
礼貌的吻别 2020-11-28 02:49

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.

相关标签:
8条回答
  • 2020-11-28 03:15

    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:

    • 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.

    Example1:

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

    Example2:

    Object* createObject() //bad
    {
        return new Object;
    }
    
    some_smart_ptr<Object> createObject() //good
    {
       return some_smart_ptr<Object>(new Object);
    }
    
    0 讨论(0)
  • 2020-11-28 03:15

    One instance where reference counting (used by shared_ptr in particular) will break down is when you create a cycle out of the pointers (e.g. A points to B, B points to A, or A->B->C->A, or etc). In that case, none of the objects will ever be automatically freed, because they are all keeping each other's reference counts greater than zero.

    For that reason, whenever I am creating objects that have a parent-child relationship (e.g. a tree of objects), I will use shared_ptrs in the parent objects to hold their child objects, but if the child objects need a pointer back to their parent, I will use a plain C/C++ pointer for that.

    0 讨论(0)
提交回复
热议问题