q0987
q0987

Reputation: 35982

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

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?

Upvotes: 5

Views: 2609

Answers (5)

ceztko
ceztko

Reputation: 15207

Let say: if your void foo(shared_ptr<int> ptr) is a general purpose library and you want to inform the user at runtime that the nullptr value is unsupported (throwing an exception) or it is treated with a different codepath yes, it's correct to check for it. If you don't need to store the shared_ptr somewhere with your foo() and you just need to ensure the function won't support null pointers, just pass a reference, for example void foo(int &integer). For the compilers I'm aware of, references are most of the times non-nullable pointers (depending often on optimization choices).

Upvotes: 0

mark
mark

Reputation: 7667

Depends on your scenario:

If the f() is a public function / API function where you have no control over what someone may pass you then yes you should check.

If the function is a private member function or is documented as requiring a valid pointer then I would use assert. It has the bnous of having no overhead in release builds and quickly shows up the problem in debug builds.

 void f( shared_ptr<T> ptr)
 {
    assert( ptr && "ptr is null!" );

    .....
 }

Upvotes: 2

Xeo
Xeo

Reputation: 131799

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.

Upvotes: 3

Puppy
Puppy

Reputation: 146930

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.

Upvotes: 5

Almo
Almo

Reputation: 15861

Yes. shared_ptr just gives you the benefit of it knowing when to release its allocated memory by counting references to it. You should still verify if it is valid before using it, assuming you don't have some other way of knowing beforehand that it will definitely not be null, but that's beside the issue of whether or not you're using a shared_ptr.

Upvotes: 0

Related Questions