A = A()有效吗?在下面调用什么运算符/方法?

duo*_*gja 3 c++ constructor copy-constructor language-lawyer c++11

给出以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码被遵守g++ 4.8.4Ubuntu 14.04

g++ -g -o test test.cpp
Run Code Online (Sandbox Code Playgroud)

并输出:

ctor
Run Code Online (Sandbox Code Playgroud)

A a = A();符合C ++标准(S)?还是仅UB因此依赖于编译器?如果该代码符合标准,则在下面调用哪些方法?A()应该什么都不返回,不是吗?

son*_*yao 7

A()执行值初始化,这将创建一个无名的临时对象。

A a = A();副本初始化a是从上述临时初始化。从输出中可以看到,由于copy elision,默认的构造A函数a此处用于直接初始化。