views:

891

answers:

2

I have a function inside a class that returns a reference to a member variable.

std::vector<uint8> & getBuffer() const
{
   return m_myBuffer;
}

Now say in another class I call this method:

int someFunction()
{
   std::vector<uint8> myFileBuffer = myFile.getBuffer();
}

This line calls the copy constructor of vector and makes me a local buffer. I do not want this, how can I instead set myFileBuffer to reference the myFile.getBuffer().

I know I can do this via pointers but wanted to use references if it is possible.

Thanks.

+4  A: 

Declare your local variable as being a reference type instead of a value type, i.e. like this ...

std::vector<uint8>& myFileBuffer = myFile.getBuffer();

... instead of like this ...

std::vector<uint8> myFileBuffer = myFile.getBuffer();
ChrisW
+7  A: 

Note since your member method is const you should be returning a const reference.

// Note the extra const on this line.
std::vector<uint8> const& getBuffer() const
{
    return m_myBuffer;
}

So to use the returned value by reference do this:

std::vector<uint8> const& myFileBuffer = myFile.getBuffer();
Martin York
RishiD