为什么返回不复制对象?

Jof*_*sey 0 c++ return copy-constructor

以下代码仅打印A::A(),但不打印A::A(const A&)operator=.为什么?

struct A
{
  A()               { cout << "A::A()" << endl; }
  A(const A& value) { cout << "A::A(const A&)" << endl; }

  A& operator=(const A& newValut)
  {
    cout << "A::operator=" << endl; 
    return *this;
  }
};

A foo()
{
  A a;      //Ok, there we have to create local object by calling A::A().
  return a; //And there we need to copy it, otherwise it will be destroyed
            //because it's local object. But we don't.
}

int main()
{
    A aa = foo(); //Also there we need to put result to the aa
                  //by calling A::A(const A&), but we don't.
}
Run Code Online (Sandbox Code Playgroud)

所以这段代码必须打印

A::A()
A::A(const A&)
A::A(const A&)
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.为什么?

我建议foo()g++没有优化的情况下没有内联.

Tom*_*m W 10

这称为"返回值优化".在这种情况下,允许编译器忽略副本.