C++11中std::addressof的使用

来源:互联网 发布:rng淘宝官方旗舰店 编辑:程序博客网 时间:2024/06/07 05:02

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/addressoftemplate<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=414class 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.htmlclass 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

0 0
原创粉丝点击