如果我有一个 A 类(它按值返回一个对象),并且两个函数 f() 和 g() 仅在它们的返回变量上有所不同:
class A
{
public:
A () { cout<<"constructor, "; }
A (const A& ) { cout<<"copy-constructor, "; }
A& operator = (const A& ) { cout<<"assignment, "; }
~A () { cout<<"destructor, "; }
};
const A f(A x)
{A y; cout<<"f, "; return y;}
const A g(A x)
{A y; cout<<"g, "; return x;}
main()
{
A a;
A b = f(a);
A c = g(a);
}
现在当我执行 line 时A b = f(a);
,它输出:
copy-constructor, constructor, f, destructor
, 假设 f() 中的对象 y 是直接在目标(即对象 b 的内存位置)创建的,并且不涉及临时对象,这很好。
当我执行 line 时A c = g(a);
,它输出:
copy-constructor, constructor, g, copy-constructor, destructor, destructor,
.
所以问题是为什么在 g() 的情况下不能直接在 c 的内存位置创建对象,就像调用 f() 时发生的那样?为什么它在第二种情况下调用一个额外的复制构造函数(我认为这是因为临时的参与)?