When to use shared_ptr and when to use raw pointers?

后端 未结 10 1377
情歌与酒
情歌与酒 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:14

    Generally, I would avoid using raw pointers as far as possible since they have very ambiguous meaning - you might have to deallocate the pointee, but maybe not, and only human-read and -written documentation tells you what the case is. And documentation is always bad, outdated or misunderstood.

    If ownership is an issue, use a smart pointer. If not, I'd use a reference if practicable.

提交回复
热议问题