简体   繁体   中英

construction and destruction of parameterized constructor argument?

Here, i am getting different out on different compiler, why is that? On msvc compiler, there i'm getting extra destructor statement?

Why i'm getting this behaviour? Am i missing something?

i had looked many question on stackoverflow, but i can't find anything related to my problem?

i also tried to look for duplicate, but didn't find one.

class A {
public:
    A() 
    {
        std::cout << "A::constructor" << "\n";
    }

    ~A() 
    {
        std::cout << "A::Destructor" << "\n";
    }

int x = 0;
int y = 0;
};
class B {
public: 

A   member_var_1;
int member_var_2;

    B()
    {
        std::cout << "B::constructor" << '\n';
    }

    B(A a, int b)
    {
        member_var_1 = a;
        member_var_2 = b;
        std::cout << "B(A, int)::constructor " << '\n';
    }

    ~B() 
    {
        std::cout << "B::destructor" << '\n';
    }

};
int main()
{
    B v1 {A(), 5};
}

GCC output:

A::consturctor         // parameterized constructor first argument constructor 
A::consturctor         // construction of B's class member (member_var_1)
B(A, int)::consturcotr // B class parameterized constructor
A::Destructor          // Destruction of argument of parameterized constructor
B::destructor          // object goes out of scope, so B destructor called
A::Destructor          // B's Destructor called member's destructor

MSVC output:

A::consturctor
A::consturctor
B(A, int)::consturcotr 
A::Destructor
A::Destructor         // what is it destroying? if i define a "class A" copy constructor, then i don't get this output. 
B::destructor
A::Destructor

Since you're using C++17 and there is mandatory copy elision from C++17(&onwards), the extra destructor call must not be there.

A msvc bug has been reported as:

MSVC produces extra destructor call even with mandatory copy elision in C++17


Note that if you were to use C++11 or C++14, then it was possible to get an extra destructor call because prior to c++17 there was no mandatory copy elision and the parameter a could've been created using the copy/move constructor which means that you'll get the fourth destructor call as expected. You can confirm this by using the -fno-elide-constructors flag with other compilers. See Demo that has a contrived example of this.

B v1 {A(), 5};

In MSCV compiler, first, the construction of temporary A() is happening then it is elided to to "a" argument of parameterized constructor. that's why the extra destruction is happening for this temporary but it shouldn't be here because it is done implicitly. So it is a bug in MSCV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM