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

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** overload
	f(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 10

	return 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;
}

GitHubhttps://github.com/fengbingchun/Messy_Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值