C ++ simple function assignment

I tried to understand how this distribution works in C ++:

Test other = toto();

This is the complete source code:

#include <iostream>

class Test
{
public:
    Test()
    {
        j = i++;
        std::cout<<"default constructor "<<j<<std::endl;
    }

    Test(const Test&)
    {
        std::cout<<"constuctor by copy "<<j<<std::endl;
    }
    Test & operator=(const Test&)
    {
        std::cout<<"operator = "<<j<<std::endl;
        return *this;
    }
    int j;
    static int i;
};

int Test::i = 0;

Test toto()
{
    Test t;
    return t;
}

int main()
{
    Test other = toto();
    std::cout<<other.j<<std::endl;
    Test another;
    return 0;
}

The code is not used by the copy constructor or the = operator, so I don’t understand how this works ... I used gcc 4.7.0

Thranks for your help :)

Jerome

+3
source share
2 answers

Format semantics:

Test other = toto();

includes multiple copies (but not the destination). The compiler is allowed however, all other instances exclude copies; almost all compilers do this optimization.

More specifically, the standard does not indicate where class type values ​​are returned, but the usual solution is for the calling space and pass a hidden pointer to it in the function. Without the above optimizations:

Test
toto()
{
    Test t;
    return t;
}

t, return t , . ( NRVO) , , t, t. (, , t, .)

:

Test t = toto();

Test, toto, t . , t toto, .

+7

, , .

+3

All Articles