Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I check boost::shared_ptr or std::shared_ptr before I use it?

Tags:

c++

boost

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?

like image 452
q0987 Avatar asked Mar 15 '12 20:03

q0987


2 Answers

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.

like image 136
Puppy Avatar answered Nov 14 '22 22:11

Puppy


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.

like image 26
Xeo Avatar answered Nov 14 '22 23:11

Xeo