Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 - Performance difference in pointer checking - smart pointers [closed]

Is there any difference between testing a smart pointer, e.g. shared_ptr, using operator bool

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

and using operator == ?

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

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

like image 761
Radek Liska Avatar asked May 20 '26 19:05

Radek Liska


1 Answers

In gccv4.8:

#include <memory>

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

produces 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;
}

produces assembly code:

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

Consequently, it makes no difference in a decent modern compiler.

Live Demo by Jonathan Wakely

like image 185
101010 Avatar answered May 22 '26 09:05

101010



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!