在打印 "Here" 之前,不应该销毁临时 A(3) 吗?

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

不应该在打印 "Here" 之前销毁临时 A(3) 吗?

#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';
}

输出:

A(1)
A(2)
A(3)
Here
~A() 3
~A() 2
~A() 1

Live example

A(3)不是临时对象,而是A类型的对象A。与此逻辑相同:

A a[2] = { A(1), A(2) }, a2(3);

我实际上并不知道你被允许这样做。

作为@neil-kirk 回复的扩展,A(3) 不是临时的原因是原始行

A a[2] = { A(1), A(2) }, A(3);

实际上是两个变量a[]A

的shorthand声明
A a[2] = { A(1), A(2) };
A A(3);

与您的做法类似

int a = 1, b = 2;

int a = 1;
int b = 2;