void f(boost::shared_ptr<int> ptr)
{
if (ptr) // should we check?
// do something
}
void f2(int *p)
{
if (p) // good practice to check before using it
// do something
}
Question: Should we validate shared_ptr
before we use it?
No. If it is in the contract of the function that it must be valid, then the quickest way to bring attention to the fact that the caller has a bug is to crash. Fail as early as you can.
Depends on whether it's actually a possibility during normal program execution that the shared_ptr
is null. If not, push the responsibility as a precondition on the user of f
and maybe assert(ptr);
. Note that it's not only applicable to shared_ptr
, but any pointer use really. Although you maybe should just use references here.
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