0

I am still little bit confused by returning a const reference. Probably, this has been already discussed, however let's have following code as I did not find the same:

#include <vector>
#include <iostream>

struct A
{
    int dataSize;
    std::vector<char> data;
};

class T
{
public:
    T();
    ~T();
    const A& GetData();
private:
    A dataA;
};

T::T() : dataA{1}
{
}

T::~T()
{
}

const A& T::GetData()
{
    return dataA;
}

void main()
{
    T t;
    A dataReceivedCpy = {};
    dataReceivedCpy = t.GetData();

    const A& dataReceivedRef = t.GetData();
    std::cout << dataReceivedRef.dataSize << std::endl;
}

What exactly happens, when I call

dataReceivedCpy = t.GetData();

Is this correct? From my point of view, it is and a copy of the requested struct is made, am I right?

On the other hand,

const A& dataReceivedRef = t.GetData();

returns a reference to object member, it is correct, unless the T object is not destructed. Am I right?

Dom
  • 532
  • 1
  • 9
  • 23
  • Is there any reason that you default-construct `dataReceivedCpy` and then assign it, rather than simply constructing it directly from `t.getData()`? i.e. `A dataReceivedCpy{ t.getData() };` – underscore_d Aug 08 '16 at 14:10
  • No, just for explicity and demonstration purphose... (in code I use the construct above is the dataReceivedCpy a member of another class, where the getData is called). – Dom Aug 08 '16 at 14:24

1 Answers1

0

Yes, your understanding sounds correct.

dataReceivedCpy = t.GetData();

calls a copy assignment operator to put a copy of t.dataA in dataReceivedCpy.

const A& dataReceivedRef = t.GetData();

does no copying and makes dataReceivedRef a reference to t.dataA. It is valid for the lifetime of t.

aschepler
  • 70,891
  • 9
  • 107
  • 161