jeudi 4 juin 2020

C++11 move constructor was omitted in optimization phase

If you run the following C++ codes in both MSVC debug and release configuration. You can get different gCounter result. See below.

#include <stdio.h>

int gCounter = 0;

class Test
{
public:
    Test() 
    {
        printf("constructor\n");
        gCounter++;
    }
    Test( const Test& ) 
    {
        printf("copy constructor\n");
        gCounter++;
    }
    Test( Test&& ) 
    {
        printf("move constructor\n");
        gCounter++;
    }
    Test& operator=( Test& ) 
    {
        printf("assignment\n");
        gCounter++;
    }
    Test& operator=( Test&& ) 
    {
        printf("move assignment\n");
        gCounter++;
    }
    ~Test() {}
};

Test case1()
{
    Test t = Test();
    return t;
}

int main()
{
    case1();
    printf( "%d\n", gCounter );
    return 0;
}

Debug Result:

constructor
move constructor
2

Release Result:

constructor
1

I am surprise to see the result is different. Is it expected behavior? Does it lead to a big issue, if put some critical logical within move constructor? Is there anyone can help?

Aucun commentaire:

Enregistrer un commentaire