Currently learning about efficiency in C++ and wondered about the efficiency of returning parameters in methods.
Imagine a Vector3f class with an add method.
Code One:
Vector3f Vector3f::add(const Vector3f &rhs) const {
Vector3f result;
result.x(x() + rhs.x());
result.y(y() + rhs.y());
result.z(z() + rhs.z());
return result;
}
Code Two:
Vector3f Vector3f::add(const Vector3f &rhs) const {
return Vector3f(
x() + rhs.x(),
y() + rhs.y(),
z() + rhs.z());
}
I know that the second code segment is more efficient, and I was hoping someone could give me a definitive answer as to why. I'm sure it's something to do with temporary objects.