M
matthias_k
Hello,
I'm wondering if returning const references to a class member is
generally faster than returning a copy of the object.
Consider this code:
class A
{
std::string data;
public:
const std::string& get_data() const { return data; }
}
versus
class B
{
std::string data;
public:
std::string get_data() const { return data; }
}
If I now have this code:
// ...
A a;
B b;
std::string str = a.get_data();
std:.string str = b.get_data();
Which assignment will be faster? My first impression was, that since (I
guess) data is not copied in A::get_data but returned by reference, we
save one call of a copy constructor. But is this also the case in
"reality"? Which version would you prefer?
Thanks,
Matthias
I'm wondering if returning const references to a class member is
generally faster than returning a copy of the object.
Consider this code:
class A
{
std::string data;
public:
const std::string& get_data() const { return data; }
}
versus
class B
{
std::string data;
public:
std::string get_data() const { return data; }
}
If I now have this code:
// ...
A a;
B b;
std::string str = a.get_data();
std:.string str = b.get_data();
Which assignment will be faster? My first impression was, that since (I
guess) data is not copied in A::get_data but returned by reference, we
save one call of a copy constructor. But is this also the case in
"reality"? Which version would you prefer?
Thanks,
Matthias