RishiD
RishiD

Reputation: 2168

C++ How can I get a return a reference and save the refence as a local variable in a function?

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.

Upvotes: 2

Views: 3160

Answers (2)

Loki Astari
Loki Astari

Reputation: 264381

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();

Upvotes: 8

ChrisW
ChrisW

Reputation: 56113

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();

Upvotes: 4

Related Questions