参考http://en.wikipedia.org/wiki/Copy_elision
我运行以下代码:
#include <iostream>
struct C {
C() {}
C(const C&) { std::cout << "Hello World!\n"; }
};
void f() {
C c;
throw c; // copying the named object c into the exception object.
} // It is unclear whether this copy may be elided.
int main() {
try {
f();
}
catch(C c) { // copying the exception object into the temporary in the exception declaration.
} // It is also unclear whether this copy may be elided.
}
我得到的输出:
Gaurav@Gaurav-PC /cygdrive/d/Trial
$ make clean
rm -f Trial.exe Trial.o
Gaurav@Gaurav-PC /cygdrive/d/Trial
$ make
g++ -Wall Trial.cpp -o Trial
Gaurav@Gaurav-PC /cygdrive/d/Trial
$ ./Trial
Hello World!
Hello World!
我知道编译器可能已经通过不必要的复制优化了代码,而这里没有这样做。
但我想问的是,two calls to the copy constructor
是如何制造的?
catch(C c)
- 由于我们是按值传递的,因此这里调用了复制构造函数。
但是throw c
如何调用复制构造函数呢?有人可以解释吗?