c++ - 可以抛出具有私有(private)拷贝构造函数的对象吗?

标签 c++ visual-studio-2010 exception private copy-constructor

我遇到了一些我不清楚的异常问题。在 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/

相关文章:

c++ - 二维数组动态数组的运行时错误

c++ - xgboost构建错误: parameter packs not expanded with ‘...’ :

java - 应用程序在 Activity.onCreate() Java android 之前异常崩溃

python - 编写检查所有 pandas DataFrame 列值是否满足特定值?

c++ - 在 C++ 中添加整数输出?

c++ - C++ Windows 字符串转换混淆 WString 和 LPCWSTR

visual-studio-2010 - Visual Studio 不显示 SVG 图像作为背景

visual-studio-2010 - Silverlight 4 : Resolving Microsoft. Silverlight.CSharp.targets 未找到?

c++ - CMFCButton.SetToolTip() 崩溃

c# - JetBrains.ReSharper.TaskRunnerFramework.dll 中的“System.IO.EndOfStreamException”