Most portable and reliable way to get the address of variable in C++

前端 未结 2 1125
情书的邮戳
情书的邮戳 2020-12-11 05:29

Using & to get an address of a variable can be problematic if the variable type has overloaded operator&(). For example, _com_ptr_ has

相关标签:
2条回答
  • 2020-12-11 05:49

    Boost addressof is implemented with that reinterpret_cast trick so I'd say it's probably portable and standard-conforming.

    Here you can see the code in question.

    0 讨论(0)
  • 2020-12-11 06:02

    It is standard-complaint. The issue was brought to the attention of the ISO C++ committee in relation to problems with offsetof implementations that broke on this. Amongst the solutions considered were tightening the POD definition, or adding an extra restriction on types to be used with offsetof. Those solutions were rejected when the reinterpret_cast solution was brought up. Since this offered a standard-compliant way around the problem, the committee did not see a need to add extra requirements to the offsetof, and left fixes to the implementations.

    0 讨论(0)
提交回复
热议问题