3

We have a large legacy codebase with commonly referenced pointer types that are, for various reasons, better suited to being shared_ptrs.

shared_ptrs are nice drop-in replacements for regular pointers except for NULL checks. Throughout the code we have regular NULL checks on these pointers and after conversion to shared_ptrs these null checks will always pass.

Does anybody have a nice way of automatically detecting these cases: if (foo == NULL) // when foo is a boost::shared_ptr ?

We are not yet on C++11 but will be soon.

Example:

// declared elsewhere as :   boost::shared_ptr<T> foo;
if (NULL != foo) //always true when shared_ptr.  Correct check when raw pointer
{
      foo->DoSomething();
}
4

3 回答 3

2

You could convert all the pointers to your class, which will encapsulate shared_ptr, and overload it's "operator==" function to detect NULL comparisons and count them, or handle them properly. You can either stick with this proxy class, or after counting (and for example dumping to the log file) all comparisons decide whether to switch to shared_ptr or not.

于 2013-08-13T17:22:49.650 回答
1

A colleague provided this solution, which is pretty much exactly what I'm after: Put into a common header (and added the parameters in reverse order as well)

template<typename T>
bool operator!=(int null, const boost::shared_ptr<T>& p)
{   
    typedef typename T::intentional_error error;
    return false;
}

template<typename T>
bool operator==(int null, const boost::shared_ptr<T>& p)
{
    typedef typename T::intentional_error error;
    return false;
}

Gives a compile time error at the location of all comparisons between shared_ptr and int.

于 2013-08-14T13:19:56.990 回答
-2

if (foo) should work. Also if(foo.get()) works

于 2013-08-13T17:12:32.283 回答