When to use shared_ptr and when to use raw pointers?

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

    If you don't want the callee of GimmeB() to be able to extend the lifetime of the pointer by keeping a copy of the ptr after the instance of A dies, then you definitely should not return a shared_ptr.

    If the callee is not supposed to keep the returned pointer for long periods of time, i.e. there's no risk of the instance of A's lifetime expiring before the pointer's, then raw pointer would be better. But even a better choice is simply to use a reference, unless there's a good reason to use an actual raw pointer.

    And finally in the case that the returned pointer can exist after the lifetime of the A instance has expired, but you don't want the pointer itself extend the lifetime of the B, then you can return a weak_ptr, which you can use to test whether it still exists.

    The bottom line is that there's usually a nicer solution than using a raw pointer.

提交回复
热议问题