C ++ 11 - Performance Difference in Pointer Validation - Smart Pointers

Is there any difference between testing a smart pointer eg. shared_ptr usingoperator bool

if (!smart_ptr)
{
    // ...
}

      

and using operator ==

?

if (smart_ptr == nullptr)
{
    // ...
}

      

I know the difference will be small (if any), but it can also help solve the coding style at the same time.

+3


source to share


1 answer


In gccv4.8:

#include <memory>

bool is_empty(const std::unique_ptr<int>& p) {
  return p == nullptr;
}

      

creates assembly code:

is_empty(std::unique_ptr<int, std::default_delete<int> > const&):
    cmpq    $0, (%rdi)
    sete    %al
    ret

      




#include <memory>

bool is_empty2(const std::unique_ptr<int>& p) {
  return !p;
}

      

creates assembly code:

is_empty2(std::unique_ptr<int, std::default_delete<int> > const&):
    cmpq    $0, (%rdi)
    sete    %al
    ret

      

Hence it has nothing to do with a decent modern compiler.

Live Demo Jonathan Wackeli

+5


source







All Articles