可能重复:是否
可以抛出具有私有拷贝构造函数的对象?
据我所知,当你把对象作为值时,应该创建副本.因此,如果存在,则应调用复制构造函数.如果copy ctor存在并且是私有的,那么这应该导致编译错误.这是代码示例
class Exception {
public:
Exception() {
cout << "Exception()" << endl;
}
~Exception() {
cout << "~Exception() " << endl;
}
private:
Exception(const Exception &c) {
cout << "Exception(c)" << endl;
}
};
Run Code Online (Sandbox Code Playgroud)
下一个代码应该导致编译错误.
try {
Exception local;
throw local;
} catch (...) {
}
Run Code Online (Sandbox Code Playgroud)
但是VS 2005和VS 2008都成功地编译了代码并调用私有ctor.我错了,这是非标准行为,是编译器中的错误吗?
我要大胆地说这可能是一个合法的 MSVC 10 错误。但是,我找不到这方面的参考。
\n\n这是一个测试工具:
\n\n#include <cstdlib>\n#include <string>\n#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nclass Exception {\npublic:\nException() {\n cout << "Exception()" << endl;\n}\n\n~Exception() {\n cout << "~Exception() " << endl;\n}\nprivate:\nException(const Exception &c) {\n cout << "Exception(c)" << endl;\n }\n};\n\nint main()\n{\n try {\n Exception local;\n\n int n = 42;\n\n throw local;\n } catch (...) \n {\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n由于您注意到的原因,此代码应该无法编译 - 复制构造函数是private从类的上下文外部调用的。
此代码在 MSVC 10 和 MSVC 11 Dev Preview 中成功编译。
\n\nRHEL6.2 下的 GCC 4.4.4 发出:
\n\n[xxx@yyy ~]$ gcc --version\ngcc (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)\nCopyright (C) 2010 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n[xxx@yyy ~]$ gcc hack.cpp \nhack.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nhack.cpp:17: error: \xe2\x80\x98Exception::Exception(const Exception&)\xe2\x80\x99 is private\nhack.cpp:29: error: within this context\n[xxx@yyy ~]$ \nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |