While doing programming i am using assert as well as NULL pointer validation.
But as i know assert will be useful only in DEBUG mode.
My question is suppose i have a internal pointer which i am sure cant be NULL example function returning a pointer(but the pointer is not a member of class) in such cases i can use assert
test* ptr = fun(); // return a pointer of type test
assert(ptr);
//do some operation
or NULL pointer validation
test* ptr = fun(); // return a pointer of type test
assert(ptr);
if (NULL != ptr)
{
//do some operation
}
Here which code practice is good.As per my understating it will be second one.
Because i have faced some situations where the value of ptr returns NULL due to some abnormal cases that we cant even think of.
But do we have any other better options?
The real solution depends on the semantic of the function
fun.If returning
NULLis semantically invalid, then I thinkfunshould throw an appropriate exception (such asstd::logic_error1) instead of returningNULL, and you could useasserton the call site to ensure thatfunis working fine, and if it is not working fine, then abort the program. In this way, the bug infundoesn’t propagate to the rest of the program, as it is caught immediately.However, if returning
NULLfromfunis semantically valid, then you should check the return value on the call-site usingifandassertis not really needed in this case, because you will useifanyway.1. Or you could use
std::runtime_errororstd::domain_error.