【发布时间】:2014-03-10 01:01:35
【问题描述】:
我已经开始使用 C++ 11,特别是大量使用 unique_ptr 来使代码异常安全和所有权更具可读性。在我想抛出一个 unique_ptr 之前,这通常效果很好。我有创建复杂状态的错误代码(抛出很多地方,被捕获在一个地方)。由于动态分配内存的所有权在逻辑上正在从 thrower 转移到 catcher,因此 unique_ptr 似乎是表明这一点的合适类型,并清楚地表明 catcher 已获取堆对象。至少在免费的 Visual Studio 2013 中不起作用。这是一个简化的代码示例,它不再类似于任何有用的东西,但会引发行为:
// cl /nologo /EHsc /W4 test1.cpp
#include <memory>
using std::unique_ptr;
class IError
{
public:
virtual ~IError() {};
virtual void DoStuff();
};
unique_ptr<IError> Error();
int Foo() { throw Error(); }
int main(void)
{
try {
Foo();
}
catch(unique_ptr<IError> Report)
{
Report->DoStuff();
}
return 0;
}
编译器就这样喷了:
test1.cpp
test1.cpp(13) : warning C4673: throwing 'std::unique_ptr<IError,std::default_delete<_Ty>>' the following types will n
ot be considered at the catch site
with
[
_Ty=IError
]
test1.cpp(13) : warning C4670: '_Unique_ptr_base<class IError,struct std::default_delete<class IError>,1>' : this bas
e class is inaccessible
test1.cpp(13) : error C2280: 'std::unique_ptr<IError,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,
std::default_delete<_Ty>> &)' : attempting to reference a deleted function
with
[
_Ty=IError
]
C:\bin\Visual Studio Express 2013\VC\INCLUDE\memory(1486) : see declaration of 'std::unique_ptr<IError,std::d
efault_delete<_Ty>>::unique_ptr'
with
[
_Ty=IError
]
我哪里做错了?
【问题讨论】:
-
例外是符合 RAII 的,为什么你有恐惧?正如
Syl所说,按值抛出,按引用捕获。
标签: c++ exception-handling stl unique-ptr