Should I check boost :: shared_ptr or std :: shared_ptr before using 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 check shared_ptrbefore using it?

+5
source share
5 answers

No. If in the contract of the function it must be valid, then the fastest way to pay attention to the fact that the caller has an error should fail. Failure as early as possible.

+5
source

, , shared_ptr null. , f , , assert(ptr);. , shared_ptr, . , , .

+3

:

f() - /API, , - , , .

- , assert. bnous .

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

    .....
 }
+2

. shared_ptr , , , . , , , , , shared_ptr.

0

Say: if your void foo(shared_ptr<int> ptr)is a public library and you want to tell the user at runtime that the value is nullptrnot supported (throws an exception) or is being processed by other code, yes, it is correct to check it. If you do not need to store shared_ptr somewhere with foo(), and you just need to make sure that the function does not support null pointers, just pass the link, for example void foo(int &integer). For compilers that I know of, references are most time pointers that are not null (depending on optimization preferences).

0
source

All Articles