c++ - 为什么成员函数地址离自由函数这么远?
问题描述
举个例子:https ://godbolt.org/z/gHqCSA
#include<iostream>
template<typename Return, typename... Args>
std::ostream& operator <<(std::ostream& os, Return(*p)(Args...) ) {
return os << (void*)p;
}
template <typename ClassType, typename Return, typename... Args>
std::ostream& operator <<(std::ostream& os, Return (ClassType::*p)(Args...) )
{
unsigned char* internal_representation = reinterpret_cast<unsigned char*>(&p);
os << "0x" << std::hex;
for(int i = 0; i < sizeof p; i++) {
os << (int)internal_representation[i];
}
return os;
}
struct test_debugger { void var() {} };
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}
int main() {
std::cout << "0. " << &test_debugger::var << std::endl;
std::cout << "1. " << fun_void_void << std::endl;
std::cout << "2. " << fun_void_double << std::endl;
std::cout << "3. " << fun_double_double << std::endl;
}
// Prints:
// 0. 0x7018400100000000000
// 1. 0x100401080
// 2. 0x100401087
// 3. 0x100401093
我看到成员函数的地址是0x7018400100000000000
,这是可以理解的,因为成员函数指针有 16 个字节,而自由函数0x100401080
只有 8 个字节。
但是,为什么成员函数地址0x7018400100000000000
离自由函数地址那么远0x100401080
呢?即,|0x7018400100000000000 - 0x100401080| = 0x70184000FFEFFBFEF80
?
为什么它不更接近,例如,0x100401...
而不是0x701840...
?还是我打印的成员函数地址错误?
解决方案
你的架构是小端的。地址的低字节在 的第一个字节中p
,因此您的地址被向后打印。
推荐阅读
- c# - WPF Tabcontrol 具有用于 tabitems 的扩展器功能
- python - Prometheus - 在抓取之前覆盖具有不同标签的相同指标
- docker - 限制单个 GPU 上 tensorflow 的资源
- javascript - 如何在 DataTable 数据中添加前导零
- google-chrome-extension - 从外部 html 向 chrome 扩展主机发送消息
- php - 用户注册后验证电子邮件,laravel
- go - 如何转储正在运行的 kubelet 的 goroutines 堆栈竞赛
- python - 如何在 Python 中从 Excel 中返回 PrintArea
- reactjs - 在 Babel 中配置内联图像导入
- css - CSS:在媒体查询中组合类名