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?