C++11中的std::addressof获得一个对象的实际地址,即使 operator& 操作符已被重载。它常用于原本要使用 operator& 的地方,它接受一个参数,该参数为要获得地址的那个对象的引用。一般,若operator &()也被重载且不一致的话,那么用std::addressof代替它。

std::addressof: defined in header <memory>,  address of object or function, returns the address of the object or function referenced by ref, obtains the actual address of the object or function arg. this function returns the address of ref even in the presence of an overloaded reference operator (operator&).

You use std::addressof when you have to. Sadly, "when you have to" includes anytime you are working in template code and want to turn a variable of unknown type T or T& into an honest-to-God pointer to that variable's memory.

You should use std::addressof instead of & in any template implementation taking the address of a user-defined object. Doing so is not a perfect solution as it might  cause unexpected  behavior with types relying on an overloaded& operator (some argue it is an appropriate and just  punishment for developers dabbling in this dark art) .  However, it is possible to  detect the conflict of address reporting and  template expectations in debug builds  with assert(std::addressof(t) == &t).

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "addressof.hpp"
#include <iostream>
#include <memory> // std::addressof// reference: http://en.cppreference.com/w/cpp/memory/addressof
template<class T>
struct Ptr {T* pad; // add pad to show difference between 'this' and 'data'T* data;Ptr(T* arg) : pad(nullptr), data(arg){std::cout << "Ctor this = " << this << std::endl;}~Ptr() { delete data; }T** operator&() { return &data; }
};template<class T>
void f(Ptr<T>* p)
{std::cout << "Ptr   overload called with p = " << p << '\n';
}void f(int** p)
{std::cout << "int** overload called with p = " << p << '\n';
}int test_addressof_1()
{Ptr<int> p(new int(42));f(&p);                 // calls int** overloadf(std::addressof(p));  // calls Ptr<int>* overload, (= this)return 0;
}// reference: http://www.cplusplus.com/reference/memory/addressof/
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 test_addressof_2()
{void(*pfn)(unreferenceable*) = &print; // void(*pfn)(unreferenceable*); pfn = &print;unreferenceable val{ 10 };unreferenceable* foo = &val;unreferenceable* bar = std::addressof(val);(*pfn)(foo);   // prints [null pointer](*pfn)(bar);   // prints 10return 0;
}/
// reference: http://cppisland.com/?p=414
class Buffer
{
private:static const size_t buffer_size = 256;int bufferId;char buffer[buffer_size];public:Buffer(int bufferId_) : bufferId(bufferId_) {}Buffer* operator&() { return reinterpret_cast<Buffer*> (&buffer); }  //BAD practice, only for illustration!
};template<typename T>
void getAddress(T t)
{std::cout << "Address returned by & operator: " << std::ios::hex << &t << "\n";std::cout << "Address returned by addressof: " << std::ios::hex << std::addressof(t) << "\n";
}int test_addressof_3()
{int a = 3;fprintf(stderr, "a &: %p, address of: %p\n", &a, std::addressof(a));Buffer b(1);std::cout << "Getting the address of a Buffer type: \n";getAddress(b);return 0;
}/
// reference: https://wizardforcel.gitbooks.io/beyond-stl/content/38.html
class codebreaker {
public:int operator&() const {return 13;}
};int test_addressof_4()
{codebreaker c;std::cout << "&c: " << (&c) << '\n';std::cout << "addressof(t): " << std::addressof(c) << '\n';return 0;
}

GitHub: https://github.com/fengbingchun/Messy_Test

C++11中std::addressof的使用相关推荐

  1. C++/C++11中std::string用法汇总

    C++/C++11中std::string是个模板类,它是一个标准库.使用string类型必须首先包含<string>头文件.作为标准库的一部分,string定义在命名空间std中. st ...

  2. C++11中std::async的使用

    C++11中的std::async是个模板函数.std::async异步调用函数,在某个时候以Args作为参数(可变长参数)调用Fn,无需等待Fn执行完成就可返回,返回结果是个std::future对 ...

  3. C++11中std::packaged_task的使用

    C++11中的std::packaged_task是个模板类.std::packaged_task包装任何可调用目标(函数.lambda表达式.bind表达式.函数对象)以便它可以被异步调用.它的返回 ...

  4. C++11中std::shared_future的使用

    C++11中的std::shared_future是个模板类.与std::future类似,std::shared_future提供了一种访问异步操作结果的机制:不同于std::future,std: ...

  5. C++11中std::future的使用

    C++11中的std::future是一个模板类.std::future提供了一种用于访问异步操作结果的机制.std::future所引用的共享状态不能与任何其它异步返回的对象共享(与std::sha ...

  6. 概率论中指数分布介绍及C++11中std::exponential_distribution的使用

    指数分布:在深度学习中,我们经常会需要一个在x=0点处取得边界点(sharp point)的分布.为了实现这一目的,我们可以使用指数分布(exponential distribution): p(x; ...

  7. 概率论中高斯分布(正态分布)介绍及C++11中std::normal_distribution的使用

    高斯分布:最常用的分布是正态分布(normal distribution),也称为高斯分布(Gaussian distribution): 正态分布N(x;μ,σ2)呈现经典的"钟形曲线&q ...

  8. 概率论中伯努利分布(bernoulli distribution)介绍及C++11中std::bernoulli_distribution的使用

    Bernoulli分布(Bernoulli distribution):是单个二值随机变量的分布.它由单个参数ø∈[0,1],ø给出了随机变量等于1的概率.它具有如下的一些性质: P(x=1)= ø ...

  9. C++11中std::condition_variable的使用

    <condition_variable>是C++标准程序库中的一个头文件,定义了C++11标准中的一些用于并发编程时表示条件变量的类与方法等. 条件变量是并发程序设计中的一种控制结构.多个 ...

最新文章

  1. Servlet(一)
  2. 中国剩余定理(孙子定理)的证明和c++求解
  3. 3、excel数据格式设置快捷键
  4. Linux学习之三——操作档案与目录
  5. 铃木uy125摩托车机油_济南铃木安徽发布国四新车—6480元瑞梦125、9380元UY125
  6. python变量和字符_Python变量和字符串
  7. python copy()和deepcopy()解释(import copy)
  8. 漫谈 | “黎曼猜想”和区块链加密算法到底有什么关系?
  9. 2016下半年网络规划设计师考试上午真题
  10. css实现强制不换行/自动换行/强制换行
  11. petshop学习笔记(4)
  12. 无法登录a6服务器可以修复么,航天A6登录常见问题
  13. 微信找不到nfc功能_手机的NFC如何使用?3分钟教会你!
  14. A-Webkit第四章:添加学生
  15. spring boot安装环境步骤及问题解决方式
  16. 2017年经典hadoop体系课程-徐培成-专题视频课程
  17. SecureCRT创建串口连接
  18. 《Machine Learning in Action》—— Taoye给你讲讲决策树到底是支什么“鬼”
  19. 智慧水利整体解决方案2022(ppt可编辑)
  20. html名人名言页面,网页制作:关于生命的名言警句 ― 名人名言  一品故事网,Www.07938.Come...

热门文章

  1. 第一章:点云中的滤波问题---Filters
  2. Paper5:Curved-Voxel Clustering for Accurate Segmentation of 3D LiDAR Point Clouds with Real-Time Per
  3. 【python】图像映射:单应性变换与图像扭曲
  4. c++创建包含opencv的dll供C,C#调用
  5. jvm 堆外内存_NIO效率高的原理之零拷贝与直接内存映射
  6. 【点云论文速读】最佳点云分割分析
  7. Unity导出apk出现的问题,JDK,Android SDK,NDK,无“安装模块”
  8. Unity创造没有代码的游戏学习教程
  9. 帕斯卡三角形(Pascal's triangle)
  10. 一起学Hadoop——实现两张表之间的连接操作