Copy overhead when returning (large) items?

Consider the following two implementations of the simple Matrix4x4 Identity method.

1: Matrix4x4 reference is taken as a parameter, in which data is written directly.

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 Matrix4x4 without entering any data.

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 create a Matrix Identity, I need to do

Matrix4x4 mat;
Matrix4x4::CreateIdentity(mat);

for the first option and

Matrix4x4 mat = Matrix4x4::CreateIdentity();

for the second.

The first, obviously, gives the advantage that no unnecessary copy is executed, while it does not allow using it as an rvalue; Imagine

Matrix4x4 mat = Matrix4x4::Identity()*Matrix4x4::Translation(5, 7, 6);

: , Matrix4x4::CreateIdentity();, , rvalue, ? ? , ( ) . , , ?

+4
1

, , copy elision ( NRVO 1) .

() , , , , .

, - ( , , ), .

( - , , , ), , 2. , , return .

:

  • , return - , catch catch, ( cv- ) , / . , , . NRVO, " ".

  • lvalue, elise , , , , , : , rvalue ( , , const), , , lvalue ( , ).

    , ( elision ).

+10

Source: https://habr.com/ru/post/1628120/


All Articles