问题背景
在 c++ 中,当类重载了 operator& 时,直接使用 & 运算符无法获取对象的真实内存地址,而是调用重载函数返回自定义值。
class trickyclass {
public:
int data;
// 重载的 operator& 返回假地址
trickyclass* operator&() {
return reinterpret_cast<trickyclass*>(0xdeadbeef);
}
};
int main() {
trickyclass obj;
trickyclass* addr = &obj; // 返回 0xdeadbeef,不是真实地址!
}
解决方案对比
方法对比表
| 方法 | 适用标准 | 可靠性 | 可读性 | 推荐度 |
|---|---|---|---|---|
| std::addressof | c++11+ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 类型转换技巧 | c++98+ | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ |
技术原理剖析
1. std::addressof 实现原理
标准库实现通常如下:
template<typename t>
t* addressof(t& arg) noexcept {
return reinterpret_cast<t*>(
&const_cast<char&>(
reinterpret_cast<const volatile char&>(arg)
)
);
}
2. 类型转换技巧解析

内存布局可视化
对象内存布局与地址获取

决策流程图

完整示例代码
#include <iostream>
#include <memory> // 用于 std::addressof
// 重载了 operator& 的示例类
class trickyclass {
public:
int data{42};
// 重载的 operator& 返回假地址
trickyclass* operator&() {
std::cout << "重载的 operator& 被调用\n";
return reinterpret_cast<trickyclass*>(0xdeadbeef);
}
// const 版本的重载
const trickyclass* operator&() const {
std::cout << "const 重载的 operator& 被调用\n";
return reinterpret_cast<const trickyclass*>(0xdeadbeef);
}
};
// 获取真实地址的通用函数 (c++98 兼容)
template <typename t>
t* get_real_address(t& obj) {
return reinterpret_cast<t*>(
&const_cast<char&>(
reinterpret_cast<const volatile char&>(obj)
)
);
}
int main() {
trickyclass obj;
const trickyclass const_obj;
std::cout << "=== 错误方法 ===\n";
std::cout << "&obj: " << &obj << " (错误地址!)\n";
std::cout << "&const_obj: " << &const_obj << " (错误地址!)\n\n";
std::cout << "=== 正确方法 ===\n";
// 使用 std::addressof (c++11)
std::cout << "std::addressof(obj): " << std::addressof(obj) << " (真实地址)\n";
std::cout << "std::addressof(const_obj): " << std::addressof(const_obj) << " (真实地址)\n\n";
// 使用类型转换技巧 (c++98 兼容)
std::cout << "get_real_address(obj): " << get_real_address(obj) << " (真实地址)\n";
std::cout << "get_real_address(const_obj): " << get_real_address(const_obj) << " (真实地址)\n";
// 验证地址真实性
std::cout << "\n=== 验证 ===\n";
std::cout << "obj.data: " << obj.data << " (通过真实地址访问: ";
std::cout << std::addressof(obj)->data << ")\n";
return 0;
}
编译与运行
# 编译 (需要支持 c++11) g++ -std=c++11 -o example example.cpp # 运行 ./example
预期输出
=== 错误方法 === 重载的 operator& 被调用 &obj: 0xdeadbeef (错误地址!) const 重载的 operator& 被调用 &const_obj: 0xdeadbeef (错误地址!) === 正确方法 === std::addressof(obj): 0x7ffd108a1b5c (真实地址) std::addressof(const_obj): 0x7ffd108a1b60 (真实地址) get_real_address(obj): 0x7ffd108a1b5c (真实地址) get_real_address(const_obj): 0x7ffd108a1b60 (真实地址) === 验证 === obj.data: 42 (通过真实地址访问: 42)
关键总结
- 问题本质:
operator&重载改变了&运算符的默认行为 - 解决方案:
- ✅ c++11+:优先使用
std::addressof - ✅ c++98:使用类型转换技巧
- ✅ c++11+:优先使用
- 适用场景:
- 底层内存操作和调试
- 与 c 语言库交互
- 序列化和反序列化操作
- 注意事项:
- 类型转换技巧在极端情况下可能受对齐影响
std::addressof是标准库实现,更加可靠
建议:在新项目中始终使用 std::addressof,在维护旧代码时根据需要选择合适方法。
以上就是c++获取对象真实地址的方法的详细内容,更多关于c++获取对象真实地址的资料请关注代码网其它相关文章!
发表评论