Now we know that we should follow some "best practices" when dealing with return by reference:
1. Use toto aToto = getToto() or toto aToto(getToto()), don't write toto aToto; aToto = getToto();
2. Don't return a reference to a local variable, except when you know what you are doing
3. Let member function return a reference to a member variable when the performance is really an issue, and call it with toto &aTotoRef = aToto.getTotoRef() to really take advantage of return by reference. Otherwise, return by value. Always take care of the variable holding the reference result, use it only during the life time of the object itself.
There is one last thing you may want to know, that is the RVO does not work all the time, as a result it cost you one more construction/destruction of your object when you return it by value. I won't say it's a penalty you have to pay, it's just the fair cost you have to pay as the compiler can not help you more because your code asks for more. So when RVO does not work? Well, when the compiler can not decide which is the object it needs to return at compile time. Here is an example:
toto getTotoWithParam(bool first)
{
if (first)
{
toto aToto;
return aToto;
}
else
{
toto bToto;
return bToto;
}
}
Then, when calling this function, it will show you that the RVO is not apllied.
toto a = getTotoWithParam(false);
toto constructor.
toto copy constructor.
toto destructor.
toto destructor.
The object is constructed inside the function then used to copy construct the object holding the result. Compared with the getToto() function, one more object (temporary object) is created.
toto aToto = getToto():
toto constructor.
toto destructor.
So that all about the return by value/reference that I want to tell you, I hope you now know what to do given a certain situation.
Good luck and I'd like to know what you are thinking about this.
Saturday, May 7, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment