lorniper
lorniper

Reputation: 638

function returning const reference called from another member function

I do know that returning const reference sometimes cause troubles, like the accepted answer in this thread. However, I am not sure if the following use of const reference with object returned with implicit this pointer is always safe ?

class foo
{
    private:
    std::vector<double> vec;

    public:
    const std::vector<double>& Get_vec() const
    {
       return vec;
    }

    void some_method()
    {
       const std::vector<double> & vec2 = Get_vec();  // this->Get_vec

       // do something with vec2
    }
}

Upvotes: 1

Views: 50

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311156

This statement

const std::vector<double> & vec2 = Get_vec();  

is equivalent to

const std::vector<double> & vec2 = vec;  

There is no any problem with using references to data members of a class inside its methods (I mean the method void some_method() ). In any case the life time of a reference to a data member of an object inside its method is shorter than the life time of the object itself.

Upvotes: 1

Related Questions