C++ 什么都没用?
Nothrow常量:此常量值用作 新操作员和新操作员[]表示这些功能应 失败时不引发异常,而是返回空指针 但在这个简单的示例中,C++ 什么都没用?,c++,C++,Nothrow常量:此常量值用作 新操作员和新操作员[]表示这些功能应 失败时不引发异常,而是返回空指针 但在这个简单的示例中,new抛出异常,而不是返回NULL: struct SomeStruct { SomeStruct() { std::bad_alloc exception; throw exception; } }; int _tmain(int argc, _TCHAR* argv[]) {
new
抛出异常,而不是返回NULL:
struct SomeStruct
{
SomeStruct()
{
std::bad_alloc exception;
throw exception;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
SomeStruct* somestruct;
somestruct = new (std::nothrow) SomeStruct;
return 0;
}
有什么解释吗?它只是表明,尽管有
(std::nothrow)
参数设置为new
,我们仍然需要将代码放入try…catch
块。异常不是从new
抛出的,而是从SomeStruct
c-tor抛出的
如果无法分配内存,new
将引发异常。如果在无法分配内存时使用std::nothrow
常量,new
将返回NULL
在这种情况下,您应该在继续之前检查指针NULL
值
if (somestruct == NULL)
// error
else
// continue
异常不是从
new
抛出的,而是从SomeStruct
c-tor抛出的
如果无法分配内存,new
将引发异常。如果在无法分配内存时使用std::nothrow
常量,new
将返回NULL
在这种情况下,您应该在继续之前检查指针NULL
值
if (somestruct == NULL)
// error
else
// continue
异常不是从
new
抛出的,而是从SomeStruct
c-tor抛出的
如果无法分配内存,new
将引发异常。如果在无法分配内存时使用std::nothrow
常量,new
将返回NULL
在这种情况下,您应该在继续之前检查指针NULL
值
if (somestruct == NULL)
// error
else
// continue
异常不是从
new
抛出的,而是从SomeStruct
c-tor抛出的
如果无法分配内存,new
将引发异常。如果在无法分配内存时使用std::nothrow
常量,new
将返回NULL
在这种情况下,您应该在继续之前检查指针NULL
值
if (somestruct == NULL)
// error
else
// continue
std::nothrow
表示在获取内存失败时抛出std::bad_alloc
而不是new
表达式返回nullptr
。这并不意味着new
表达式永远不会抛出
如果您的
SomeStruct
没有抛出它的构造函数,那么new
表达式将永远不会抛出。std::nothrow
意味着在获取内存失败时不会抛出std::bad_alloc
,而new
表达式将返回nullptr
。这并不意味着new
表达式永远不会抛出
如果您的
SomeStruct
没有抛出它的构造函数,那么new
表达式将永远不会抛出。std::nothrow
意味着在获取内存失败时不会抛出std::bad_alloc
,而new
表达式将返回nullptr
。这并不意味着new
表达式永远不会抛出
如果您的
SomeStruct
没有抛出它的构造函数,那么new
表达式将永远不会抛出。std::nothrow
意味着在获取内存失败时不会抛出std::bad_alloc
,而new
表达式将返回nullptr
。这并不意味着new
表达式永远不会抛出
如果您的
SomeStruct
没有抛出其构造函数,new
表达式永远不会抛出。我抛出'std::bad_alloc'来模拟同样的情况?@Andrew:在构造函数中抛出std::bad_alloc
与抛出std::bad_alloc
的实现无关,因为它无法分配内存来构造对象。@Andrew,你是在扔坏东西,但不是在模拟。要查看std::nothrow的作用,请参阅new(std::nothrow)char[std::numeric_limits::max()]
与相同字符(无std::nothrow
之间的区别。nothrow指获取可用内存时出现的异常,不是在你的构造函数中。我抛出'std::bad_alloc'来模拟同样的情况?@安德鲁:你在构造函数中抛出std::bad_alloc
与实现无关,因为它无法分配内存来构造你的对象。@安德鲁,你抛出的是bad_alloc,但不一样。要查看std::nothrow的作用,请参阅new(std::nothrow)char[std::numeric_limits::max()]
与相同字符(无std::nothrow
之间的区别。nothrow指获取可用内存时出现的异常,不是在你的构造函数中。我抛出'std::bad_alloc'来模拟同样的情况?@安德鲁:你在构造函数中抛出std::bad_alloc
与实现无关,因为它无法分配内存来构造你的对象。@安德鲁,你抛出的是bad_alloc,但不一样。要查看std::nothrow的作用,请参阅new(std::nothrow)char[std::numeric_limits::max()]
与相同字符(无std::nothrow
之间的区别。nothrow指获取可用内存时出现的异常,不是在你的构造函数中。我抛出'std::bad_alloc'来模拟同样的情况?@安德鲁:你在构造函数中抛出std::bad_alloc
与实现无关,因为它无法分配内存来构造你的对象。@安德鲁,你抛出的是bad_alloc,但不一样。要查看std::nothrow的作用,请查看new(std::nothrow)char[std::numeric_limits::max()]
与相同字符(不带std::n)之间的差异