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.
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.