7

Possible Duplicate:
Can objects with private copy constructors be thrown?

As I know, when you trow object as value, copy should be created. So copy constructor should be called if exist. If copy ctor exists and is private then this should cause compilation error. Here is code sample

class Exception {
public:
Exception() {
    cout << "Exception()" << endl;
}

~Exception() {
    cout << "~Exception() " << endl;
}
private:
Exception(const Exception &c) {
        cout << "Exception(c)" << endl;
    }
};

And next code should lead to compilation error.

try {
        Exception local;

        throw local;
    } catch (...) {
    }

But both in VS 2005 and VS 2008 succesfully compile that code and call private ctor. Am I wrong that this is non standard behaviour and is an error in compiler?

4

2 回答 2

0

我要在这里冒昧地说这可能是一个合法的 MSVC 10 错误。但是,我找不到这方面的参考。

这是一个测试工具:

#include <cstdlib>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

class Exception {
public:
Exception() {
    cout << "Exception()" << endl;
}

~Exception() {
    cout << "~Exception() " << endl;
}
private:
Exception(const Exception &c) {
        cout << "Exception(c)" << endl;
    }
};

int main()
{
    try {
        Exception local;

        int n = 42;

        throw local;
    } catch (...) 
    {
    }
}

由于您注意到的原因,此代码应该无法编译 - 复制构造函数是private从类的上下文外部调用的。

此代码在 MSVC 10 和 MSVC 11 Dev Preview 中成功编译。

RHEL6.2 下的 GCC 4.4.4 发出:

[xxx@yyy ~]$ gcc --version
gcc (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[xxx@yyy ~]$ gcc hack.cpp 
hack.cpp: In function ‘int main()’:
hack.cpp:17: error: ‘Exception::Exception(const Exception&)’ is private
hack.cpp:29: error: within this context
[xxx@yyy ~]$ 
于 2012-06-05T14:12:28.997 回答
0

该标准规定异常必须是可复制的,因为 throw 可能会复制。您已将复制构造函数设为私有,因此不应编译。

然而,它并没有说明 throw 的实现是复制所必需的——事实上,它可能被省略,或者在 C++11 中甚至被移动。因此,尽管 MSVC 应该以不符合标准为由拒绝编译代码,但它仍然会这样做,因为它可以使用 MSVC 的处理方式。

这不太可能是错误,而只是 VC 不符合标准的情况。

于 2012-06-05T15:55:27.863 回答