Consider the following two implementations of a simple Matrix4x4 Identity method.
1: This one takes a Matrix4x4 reference as parameter, in which the data is directly written.
static void CreateIdentity(Matrix4x4& outMatrix) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
outMatrix[i][j] = i == j ? 1 : 0;
}
}
}
2: This one returns a Matrix4x4 without taking any input.
static Matrix4x4 CreateIdentity() {
Matrix4x4 outMatrix;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
outMatrix[i][j] = i == j ? 1 : 0;
}
}
return outMatrix;
}
Now, if I want to actually create an Identity-Matrix I have to do
Matrix4x4 mat;
Matrix4x4::CreateIdentity(mat);
for the first variant and
Matrix4x4 mat = Matrix4x4::CreateIdentity();
for the second.
The first one obviously yields the advantage that not a single unneccesary copy is done, while it does not allow to use it as an rvalue; imagine
Matrix4x4 mat = Matrix4x4::Identity()*Matrix4x4::Translation(5, 7, 6);
Final Question: Is there a way to avoid unneccesary copies when using Methods like Matrix4x4::CreateIdentity();
whenever possible while still allowing to use the method as an rvalue as in my last code-example? Is it even optimised automatically by the compiler? I'm rather confused how to efficiently go about this (seemingly) simple task. Maybe I should implement both versions and use whatever is appropiate?