何时使用addressof(x)代替& x? [英] When to use addressof(x) instead of &x?

查看:115
本文介绍了何时使用addressof(x)代替& x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在获取对象地址时,如何确定是否需要addressof(x)而不是&x?

How do I decide whether I need addressof(x) instead of &x when taking the address of an object?

问题似乎令人困惑,因此需要进行澄清:

Seems like the question was confusing, so a clarification is in order:

addressof显然绕过了重载的address-of运算符. 我已经知道了.

addressof obviously bypasses the overloaded address-of operator. I'm already aware of that.

我想知道的是:
我怎么知道那是我真正想要的? (尤其是在模板中时,等等)

What I want to know is:
How do I know if that's what I really want to do? (Especially when inside a template, etc.)

是否有某种规则"可以帮助我确定何时需要addressof而不是&?
毕竟,它们都返回对象的地址",所以我什么时候使用哪个?

Is there some kind of "rule" that helps me figure out when I need addressof instead of &?
After all, they both return the "address of" the object, so when do I use which?

推荐答案

在需要时使用std::addressof.可悲的是,在需要时"包括您在模板代码中使用的任何时间,并且希望将未知类型TT&的变量转换为指向该变量的内存的诚实指针.

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.

由于C ++委员会愚蠢地允许引用运算符的重载(出于很少的合法目的),用户可能用某种类型实例化您的模板,而您不能使用引用运算符来获取实际的指针. std::addressof是一种解决使用此可疑C ++功能的用户的方法,以执行该语言从一开始就应保证的工作.

Because the C++ committee foolishly allowed the overloading of the reference operator (to little legitimate purpose), it is possible for a user to instantiate your template with some type that you can't use the reference operator to get an actual pointer to. std::addressof is a way to work around users who use this dubious C++ feature in order to do what the language should have guaranteed to work to begin with.

简而言之,它是针对语言愚蠢的库修复程序.如果要确保用户不会破坏您的代码,请在模板代码而不是&中使用它.如果可以信任您的用户不要使用此功能不当的功能,则可以使用&.

In short, it's a library fix for a language stupidity. Use it in template code instead of & if you want to make sure users can't break your code. If your users can be trusted not to use this ill-conceived feature, then you can use &.

这篇关于何时使用addressof(x)代替& x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆