10

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

2 Answers2

13

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.

Neil Kirk
  • 20,002
  • 5
  • 48
  • 79
  • 1
    you can do it, but after you did, you have to refer type `A` as `struct A` because just `A` would be ambiguous. – SHR Oct 18 '15 at 22:39
5

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;
Othrayte
  • 615
  • 6
  • 18