1

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
    }
}
Community
  • 1
  • 1
lorniper
  • 626
  • 1
  • 7
  • 29
  • 1
    The accepted answer states *The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed.* so unless you plan to destroy the object whats the problem? – NathanOliver Aug 10 '16 at 15:16

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335