异常和复制构造函数:C ++ [英] Exception and Copy Constructor : C++
问题描述
引用 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!
我了解编译器可能已经通过不必要的复制对代码进行了优化,而这在这里没有做.
I understand that the compiler might have optimized the code with unnecessary copying, which it is not doing here.
但是我想问的是,如何两次调用复制构造函数
?
catch(C c)
-由于我们按值传递,因此此处将调用复制构造函数.
catch(C c)
- Since we are passing by value, hence here the copy constructor is being called.
但是在 throw c
处如何调用拷贝构造函数?有人可以解释吗?
But at throw c
how is copy constructor being called? Can someone explain?
推荐答案
throw c;
创建一个临时对象,并抛出该临时对象.临时文件的创建可以通过复制/移动构造函数进行.是的,可以删除此副本/移动.
Creates a temporary object and it is this temporary object that is thrown. The creation of the temporary might be through copy/move constructor. And yes this copy/move can be elided.
参考文献:
C ++ 11 15.1引发异常
§3:
throw-expression会初始化一个临时对象,称为异常对象,其类型是通过从throw操作数的静态类型中删除所有顶级cv限定符并进行调整来确定的类型.........
A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type.........
§5:
当抛出的对象是类对象时,即使省略了复制/移动操作(12.8),复制/移动构造函数和析构函数也应可访问.
When the thrown object is a class object, the copy/move constructor and the destructor shall be accessible, even if the copy/move operation is elided (12.8).
这篇关于异常和复制构造函数:C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!