c ++ 11 - 指针检查的性能差异 - 智能指针

Rad*_*ska 3 c++ coding-style c++11

测试智能指针(例如shared_ptr)之间有什么区别吗? operator bool

if (!smart_ptr)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

和使用operator ==

if (smart_ptr == nullptr)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我知道差异很小(如果有的话),但它也可以帮助同时决定编码风格.

101*_*010 5

在gccv4.8中:

#include <memory>

bool is_empty(const std::unique_ptr<int>& p) {
  return p == nullptr;
}
Run Code Online (Sandbox Code Playgroud)

生成汇编代码:

is_empty(std::unique_ptr<int, std::default_delete<int> > const&):
    cmpq    $0, (%rdi)
    sete    %al
    ret
Run Code Online (Sandbox Code Playgroud)
#include <memory>

bool is_empty2(const std::unique_ptr<int>& p) {
  return !p;
}
Run Code Online (Sandbox Code Playgroud)

生成汇编代码:

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

因此,它在体面的现代编译器中没有区别.

Jonathan Wakely的现场演示

  • 据我所知,asm只是"返回0"...... (5认同)