【发布时间】:2013-05-02 05:28:19
【问题描述】:
参考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 是如何调用复制构造函数的?谁能解释一下?
【问题讨论】:
标签: c++