我有一个类似
的自定义内存分配器void* Object::operator new(std::size_t size, const std::nothrow_t& nothrow_value)
{
void *p = Allocator->malloc(size);
return p;
}
由于标准说我不应该抛出异常,我不会检查分配是否成功。现在我正在模拟Allocator对象,以便malloc函数调用返回NULL。我正在使用这样的运算符:
class TestClass: public Object
{
public : TestClass()
{
}
}
testObject = new (std::nothrow)TestClass();
崩溃了,gdb的bt显示了这样的东西..这个指针突然变成了0x0。任何人都可以赦免我......如果是这种情况,我怎么能在我的代码中处理这种情况。
#0 0x000000000040acd3 in TestClass::TestClass (this=0x0) at TestAllocatable.cpp:72
#1 0x00000000004074ed in TestAllocatableFixture_Positive2_Test::TestBody (this=0x67cdc0) at TestAllocatable.cpp:238
#2 0x0000000000443c98 in void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ()
#3 0x000000000043eaf8 in void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ()
#4 0x000000000042bab8 in testing::Test::Run (this=0x67cdc0) at ../gtest/src/gtest.cc:2162
答案 0 :(得分:3)
尝试向函数添加异常规范
定义,告诉编译器这个operator new
赢了
扔:
void* Object::operator new( size_t size, std::nothrow_t ) throw();
或者如果你有C ++ 1:
void* Object::operator new( size_t size, std::nothrow_t) noexcept;
没有异常规范,编译器会假设
operator new
函数永远不会返回空指针。