When to use shared_ptr and when to use raw pointers?

后端 未结 10 1380
情歌与酒
情歌与酒 2020-11-29 16:27
class B;

class A
{
public:
    A ()
        : m_b(new B())
    {
    }

    shared_ptr GimmeB ()
    {
        return m_b;
    }

private:
    shared_ptr&l         


        
10条回答
  •  甜味超标
    2020-11-29 17:22

    The question "when should I use shared_ptr and when should I use raw pointers?" has a very simple answer:

    • Use raw pointers when you do not want to have any ownership attached to the pointer. This job can also often be done with references. Raw pointers can also be used in some low level code (such as for implementing smart pointers, or implementing containers).
    • Use unique_ptr or scope_ptr when you want unique ownership of the object. This is the most useful option, and should be used in most cases. Unique ownership can also be expressed by simply creating an object directly, rather than using a pointer (this is even better than using a unique_ptr, if it can be done).
    • Use shared_ptr or intrusive_ptr when you want shared ownership of the pointer. This can be confusing and inefficient, and is often not a good option. Shared ownership can be useful in some complex designs, but should be avoided in general, because it leads to code which is hard to understand.

    shared_ptrs perform a totally different task from raw pointers, and neither shared_ptrs nor raw pointers are the best option for the majority of code.

提交回复
热议问题