mercredi 31 octobre 2018

Returning owned pointers by reference

Suppose you are defining two classes, A and B, and B has a pointer to an instance of A, and is responsible for managing the lifetime of that instance. Like so:

class A;

class B
{
public:
    B(A *a);
    ~B() { delete m_a; }
private:
    A *m_a;
};

Would it be more appropriate for the method B::get_a to return a constant reference:

const A &get_a() const
{
    return *m_a;
}

or just return the pointer:

const A *get_a() const
{
    return m_a;
}

Aucun commentaire:

Enregistrer un commentaire