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
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.
Now, should
pIntbe null in any of iteration, then this test case will stop andpListwill 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With