Returning const references to class data

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
 
S

shez

matthias_k said:
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

For built-in types (or small user-defined types), class B will probably
be faster, although if inlining is performed, they might probably be
the same.

For expensive user-defined types (e.g., require allocation etc), class
A will probably be faster, although if inlining (and heavy
optimisation) is performed, they might probably be the same. But
usually for these types, its best to return by const reference.

-shez-
 
M

matthias_k

shez said:
For built-in types (or small user-defined types), class B will probably
be faster, although if inlining is performed, they might probably be
the same.

For expensive user-defined types (e.g., require allocation etc), class
A will probably be faster, although if inlining (and heavy
optimisation) is performed, they might probably be the same. But
usually for these types, its best to return by const reference.

-shez-

Yes, I should have clarified that I was only concerned about complex
types. But basically that's what I thought as well, thanks shez.

Regards,
Matthias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top