c++11 - Defined function returning const reference to class member and copy of the variable -
i still little bit confused returning const reference. probably, has been discussed, let's have following code did not find same:
#include <vector> #include <iostream> struct { int datasize; std::vector<char> data; }; class t { public: t(); ~t(); const a& getdata(); private: dataa; }; t::t() : dataa{1} { } t::~t() { } const a& t::getdata() { return dataa; } void main() { t t; datareceivedcpy = {}; datareceivedcpy = t.getdata(); const a& datareceivedref = t.getdata(); std::cout << datareceivedref.datasize << std::endl; }
what happens, when call
datareceivedcpy = t.getdata();
is correct? point of view, , copy of requested struct made, right?
on other hand,
const a& datareceivedref = t.getdata();
returns reference object member, correct, unless t object not destructed. right?
yes, understanding sounds correct.
datareceivedcpy = t.getdata();
calls copy assignment operator put copy of t.dataa
in datareceivedcpy
.
const a& datareceivedref = t.getdata();
does no copying , makes datareceivedref
reference t.dataa
. valid lifetime of t
.
Comments
Post a Comment