【发布时间】:2018-02-12 20:36:29
【问题描述】:
假设我有这个代码:
#include <iostream>
using namespace std;
class A{
public:
A() { cout << "In normal ctor\n"; }
A(const A& a) { cout << "In cpy ctor\n"; }
A(A&& a) { cout << "In move ctor\n"; }
~A() { cout << "In dtor\n"; }
};
A func(A a) {
return a;
}
void main(){
A a1;
A a2 = func(a1);
}
输出如下:
In normal ctor
In cpy ctor
In move ctor
In dtor
In dtor
In dtor
现在我无法理解函数“func”内部发生的事情。
当 a1 被发送到函数时,函数不会通过 Ref 接收它,而是“创建”它自己的 a1 版本,即“a”。
这就是为什么当函数结束时,对象“死亡”并成为析构函数。
那么为什么不把它也交给构造器呢? (假设那里真的创建了一个本地对象)
是否有任何在幕后发生的复制?
提前致谢!
【问题讨论】:
-
“那么为什么不把它也交给构造函数”它确实
In cpy ctor -
but rather it "creates" it's own version,是的,它被称为复制构造,你在In cpy ctor中看到它。 -
@tkausl 但不是因为“A a2 = func(a1)”的副本吗?它不在函数内部
-
@Martin 不,这个作业被优化为移动构造,
In move ctor。 -
@freakish 哦,我明白了,所以复制构造函数是因为函数中的“创建”而发生的?此举实际上是主要的吗? (因为它是一个 RVALUE)
标签: c++ variables constructor scope compilation