Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Automatically detecting where shared_ptr is compared to NULL

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();
}
like image 975
Ken Moynihan Avatar asked Mar 15 '26 18:03

Ken Moynihan


1 Answers

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.

like image 197
BartoszKP Avatar answered Mar 18 '26 09:03

BartoszKP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!