我遇到了一些我不清楚的异常问题。在 C++ 中,当抛出一个对象时,它首先被复制到一个临时对象,然后将临时对象传递给捕获代码。复制涉及使用对象的类复制构造函数。 AFAIK,这意味着如果一个类有一个私有(private)的复制构造函数,它就不能用作异常。但是在VS2010中,编译运行如下代码:
class Except
{
Except(const Except& other) { i = 2; }
public:
int i;
Except() : i(1) {}
};
int main()
{
try
{
Except ex1;
throw ex1; // private copy constructor is invoked
}
catch (Except& ex2)
{
assert(ex2.i == 2); // assert doesn't yell - ex2.i is indeed 2
}
return 0;
}
这合法吗?
最佳答案
这是不合法的。标准 15.1/5
If the use of the temporary object can be eliminated without changing the meaning of the program except for the execution of constructors and destructors associated with the use of the temporary object (12.2), then the exception in the handler can be initialized directly with the argument of the throw expression. When the thrown object is a class object, and the copy constructor used to initialize the temporary copy is not accessible, the program is ill-formed (even when the temporary object could otherwise be eliminated). Similarly, if the destructor for that object is not accessible, the program is ill-formed (even when the temporary object could otherwise be eliminated).
关于c++ - 可以抛出具有私有(private)拷贝构造函数的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103645/