`A a = A()` 有效吗?下面调用了哪些运算符/方法?

Is `A a = A()` valid? What operators / methods are invoked underneath?

给定以下代码:

#include <iostream>

class A {
 public:
  int x;

 public:
  A() : x(0) { std::cout << "ctor" << std::endl; }
  A(const A& o) : x(o.x) { std::cout << "copy ctor" << std::endl; }
  A& operator=(const A& o) { x = o.x; std::cout << "copy asgnmt" << std::endl; return *this; }
};

int main() {
  A a = A();
  return 0;
}

以上代码在 Ubuntu 14.04 上符合 g++ 4.8.4:

g++ -g -o test test.cpp

并输出:

ctor

A a = A(); 是否符合 C++ 标准?或者这只是 UB 因此依赖于编译器?如果该代码符合标准,那么在下面调用了哪些方法? A() 应该 return 什么都不应该,不是吗?

A() 执行 value initialization,这会创建一个无名的临时对象。

A a = A();copy initialization, a is initialized from the above temporary. As you can see from the output, the default constructor of A is used to initialize a directly here, because of copy elision