Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't the temporary A(3) be destroyed before "Here" is printed?

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

like image 670
François-Marie Arouet Avatar asked Oct 18 '15 22:10

François-Marie Arouet


2 Answers

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.

like image 148
Neil Kirk Avatar answered Sep 28 '22 09:09

Neil Kirk


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;
like image 35
Othrayte Avatar answered Sep 28 '22 08:09

Othrayte