考虑以下程序:
struct ghost
{
// ghosts like to pretend that they don't exist
ghost* operator&() const volatile { return 0; }
};
int main()
{
ghost clyde;
ghost* clydes_address = &clyde; // darn; that's not clyde's address :'(
}
我如何获得clyde
的地址?
我正在寻找一种同样适用于所有类型对象的解决方案。 C++03 解决方案会很好,但我也对 C++11 解决方案感兴趣。如果可能,让我们避免任何特定于实现的行为。
我知道 C++11 的 std::addressof
函数模板,但对在这里使用它不感兴趣:我想了解标准库实现者如何实现这个函数模板.
最佳答案
使用 std::addressof
.
您可以将其视为在幕后执行以下操作:
- 将对象重新解释为对字符的引用
- 取那个地址(不会调用重载)
- 将指针转换回您的类型的指针。
现有的实现(包括 Boost.Addressof)正是这样做的,只是额外注意 const
和 volatile
限定。
关于c++ - 当 operator& 重载时,如何可靠地获取对象的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6494591/