mercredi 21 septembre 2022

lifetime of function local variable and temporary object

I'm getting the different behaviour on different compliler, on GCC temporary object and local variable are destroyed in the end of an expression but on MSVC compiler, local variable and temporary object are destroyed at the end of function. why i'm getting this different behaviour ? see live demo

struct X{ 
    X() 
    {
        std::cout << "X::X() " << '\n';
    }

    X(const X& arg)
    {
        std::cout << "X::Copy" << '\n';
    }

    X(X&& arg)
    {
        std::cout << "C::move" << '\n';
    }
        
    ~X(){ std::cout << "Goodbye, cruel world!\n"; }

};
X  f(X  x){
    X arg{};
    std::cout << "Inside f()\n";
    return x;
}
void g(X  x){
    std::cout << "Inside g()\n";
}

int main()
{
    X arg{};
    g(f(arg));
}

GCC output:

X::X() 
X::Copy
X::X() 
Inside f()
C::move
Goodbye, cruel world!
Inside g()
Goodbye, cruel world!
Goodbye, cruel world!
Goodbye, cruel world!

MSCV output:

X::X() 
X::Copy
X::X() 
Inside f()
C::move
Goodbye, cruel world!
Goodbye, cruel world!
Inside g()
Goodbye, cruel world!
Goodbye, cruel world!

Aucun commentaire:

Enregistrer un commentaire