【C++】 std::addressof的使用

template <class T> T* addressof (T& ref) noexcept;
Address of object or function
Returns the address of the object or function referenced by ref.

This function returns the address of ref even in the presence of an overloaded reference operator (operator&).

// addressof example
#include <iostream>
#include <memory>

struct unreferenceable {
  int x;
  unreferenceable* operator&() { return nullptr; }
};

void print (unreferenceable* m) {
  if (m) std::cout << m->x << '\n';
  else std::cout << "[null pointer]\n";
}

int main () {
  void(*pfn)(unreferenceable*) = std::addressof(print);

  unreferenceable val {10};
  unreferenceable* foo = &val;
  unreferenceable* bar = std::addressof(val);
  unreferenceable* tee = reinterpret_cast<unreferenceable*>(&(val.x));
    
  std::cout << &val << std::endl;
  std::cout << foo << std::endl;
  std::cout << bar << std::endl;
  std::cout << tee << std::endl;
    
  (*pfn)(foo);   // prints [null pointer]
  (*pfn)(bar);   // prints 10
  (*pfn)(tee);   // prints 10

  return 0;
}

输出结果为:

:g++ -std=c++11 -O0 main.cc -o main
:./main
0x0
0x0
0x7ffee3806988
0x7ffee3806988
[null pointer]
10
10

注意类型重载:

unreferenceable* operator&() { return nullptr; }
发布了423 篇原创文章 · 获赞 14 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/105478352