Shouldn't the temporary A(3)
be destroyed before "Here" gets printed?
#include <iostream>
struct A
{
int a;
A() { std::cout << "A()" << std::endl; }
A(int a) : a(a) { std::cout << "A(" << a << ")" << std::endl; }
~A() { std::cout << "~A() " << a << '\n'; }
};
int main()
{
A a[2] = { A(1), A(2) }, A(3);
std::cout << "Here" << '\n';
}
Output:
A(1)
A(2)
A(3)
Here
~A() 3
~A() 2
~A() 1
Live example
A(3)
is not a temporary object, but an object of type A
called A
. It's the same logic as this:
A a[2] = { A(1), A(2) }, a2(3);
I didn't actually know you were allowed to do that.
As an extension to @neil-kirk's reply the reason A(3)
is not a temporary is that the original line
A a[2] = { A(1), A(2) }, A(3);
is really a shorthand declaration of two variables a[]
and A
A a[2] = { A(1), A(2) };
A A(3);
similar to how you might do
int a = 1, b = 2;
or
int a = 1;
int b = 2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With