4

I have use case scenario.

List* pList = new List();    
for (...)
{

 Integer* pInt = new Integer();
 ASSERT_TRUE(pInt != NULL);
 pList->Add(*pInt);

}

Now, should pInt be null in any of iteration, then this test case will stop and pList will not be freed.

Is there any way to free up pList when ASSERT_TRUE executes?

Thanks

Fraser
  • 74,704
  • 20
  • 238
  • 215
yogesh singh
  • 101
  • 1
  • 9
  • The answer to all your resource management: RIIA. Don't ever write `new`/`delete` anymore in modern c++ (except `= delete;`) – sehe Sep 26 '12 at 21:11

2 Answers2

3

If you can use lambdas, you could do:

ASSERT_TRUE(pInt != nullptr)
    << [pList]()->std::string { delete pList; return "Your error message."; }();

The lambda is only executed if the assertion fails.

However, the best option is probably to use a std::unique_ptr or similar smart pointer rather than raw pointers and avoid the worry altogether.

Fraser
  • 74,704
  • 20
  • 238
  • 215
2

Now, should pInt be null in any of iteration, then this test case will stop and pList will not be freed.

Assuming you didn't override the new operator (if you did, you probably wouldn't be asking about this), and assuming your compiler is not buggy, pInt will never be null. On failure, new throws a std::bad_alloc exception, it doesn't return null.

Moreover, assertions are for things that should always hold (as is the case), no matter what. An assertion failure is a bug. There's no point in adding code to clean up after an assertion failure: just fix the bug instead.

Now to the freeing... The sample code provided can just forget new and use automatic objects:

List pList;
for (...)
{

 Integer pInt = Integer();
 pList.Add(pInt);
}
Community
  • 1
  • 1
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510