是否可以抛出具有私有复制构造函数的对象? [英] Can objects with private copy constructors be thrown?

查看:173
本文介绍了是否可以抛出具有私有复制构造函数的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我不清楚的例外问题。在C ++中,当一个对象被抛出时,它首先被复制到一个临时对象,然后临时对象被传递给捕获代码。复制涉及使用对象的类复制构造函数。 AFAIK,这意味着如果一个类有一个私有拷贝构造函数,它不能用作异常。但是,在VS2010中,以下代码编译并运行:

 类除了
{
除了& other){i = 2; }
public:
int i;
Except():i(1){}
};

int main()
{
try
{
除ex1;
throw ex1; // private copy constructor is invoked
}
catch(except& ex2)
{
assert(ex2.i == 2); // assert does not yell - ex2.i is actually 2
}
return 0;这是合法的吗?

}

h2_lin>解决方案

这不合法。标准15.1 / 5


如果临时对象的使用可以消除而不改变
程序的意义,执行构造函数
和与使用临时对象
(12.2)相关联的析构函数,那么在处理程序中的异常可以直接用
与throw表达式的参数初始化。 当抛出的对象是
类对象,并且用于初始化
临时副本的副本构造函数不可访问时,程序是错误的
(即使$ b $否则可以消除临时对象)。类似地,如果该对象的
析构函数不可访问,则程序是
不合格的(即使临时对象可能是
消除)。



I've come across some exceptions issue that is unclear to me. In C++, when an object is thrown it is first copied to a temporary object, and the temporary object is then passed to the catching code. The copy involves the use of the object's class copy constructor. AFAIK, this means that if a class has a private copy constructor, it can't be used as an exception. However, in VS2010, the following code compiles and runs:

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;
}

Is this legal?

解决方案

It's not legal. Standard 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).

这篇关于是否可以抛出具有私有复制构造函数的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆