Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to free memory after ASSERT_TRUE in gtest

Tags:

c++

googletest

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

like image 268
yogesh singh Avatar asked Oct 26 '25 14:10

yogesh singh


2 Answers

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.

like image 150
Fraser Avatar answered Oct 28 '25 04:10

Fraser


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);
}
like image 30
R. Martinho Fernandes Avatar answered Oct 28 '25 04:10

R. Martinho Fernandes