SinisterMJ
SinisterMJ

Reputation: 3509

What does the & do in this case?

I had the following code today:

std::vector<float>& vecHighRes = highRes->getSamples();

PMHighResolution.cpp / .h

std::vector<float>& getSamples();
static std::vector<float> fSamples;

std::vector<float>& PMHighResolution::getSamples()
{
    return fSamples;
}

Why would I need the & twice there? in the return I assume because it otherwise generates a copy of the vector to be returned, but why do I need it in the assign operator (

std::vector<float>& vecHighRes = highRes->getSamples(); ) ?

Upvotes: 1

Views: 100

Answers (3)

billz
billz

Reputation: 45450

getSamples() returns a reference

std::vector<float>& vecHighRes = highRes->getSamples(); 

with & , vecHighRes is a reference to std::vector<float>. No fSamples is copied after highRes->getSamples() gets called.

std::vector<float> vecHighRes = highRes->getSamples(); 

In this case, vecHighRes is a vector of float. getSamples will make a whole vector copies.

You may see lots of this kind forms in function parameter

 void func(std::vector<float>& vecHighRes, // pass by reference only. only reference is copied
           std::vector<float> vecHighRes2) // pass by value, whole vector is copied   

Upvotes: 1

ogni42
ogni42

Reputation: 1276

Because, in that way you are assigning a reference to a reference. If you'd omit the reference for vecHighRes, the assignment operator will copy the contents of the vector returned by get samples to the new vector.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227518

The & on the LHS means that vecHighRes is a reference:

std::vector<float>& vecHighRes = highRes->getSamples();

If you had omitted the &, vecHighRes would be a copy of vector fSamples, constructed from the reference returned by getSamples.

It is the same as this:

int a = 42;
int& b = a;  // b is a reference to a
int c = b;   // c is a copy of a

Upvotes: 7

Related Questions