以这个例子为例: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++ - 为什么成员函数地址与自由函数相距如此远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59779964/