Pergunta

I have a custom memory allocator written something like

void* Object::operator new(std::size_t size, const std::nothrow_t& nothrow_value)
{
  void *p = Allocator->malloc(size);
  return p;
}

Since the standard says I shouldn't throw an exception, I do not check whether allocation has been successful or not. Now I'm mocking Allocator object so that malloc function call returns me NULL. I'm using this operator something like this :

class TestClass: public Object
{
  public : TestClass()
  {
  }
}
testObject = new (std::nothrow)TestClass();

It is crashing here and bt of gdb shows something like this.. This pointer suddenly goes 0x0. can anybody expalin me..! If this is the case how can i handle this situation in my code.

#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
Foi útil?

Solução

Try adding an exception specification to the function definition, to tell the compiler that this operator new won't throw:

void* Object::operator new( size_t size, std::nothrow_t ) throw();

or if you have C++1:

void* Object::operator new( size_t size, std::nothrow_t) noexcept;

Without the exception specification, the compiler assumes that the operator new function will never return a null pointer.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top