c++ - 为什么成员函数地址与自由函数相距如此远?

标签 c++ pointers memory member-function-pointers non-member-functions

以这个例子为例: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/

相关文章:

java - 通过 jni 将枚举 native 类型公开给 java?

c++ - 派生类不会覆盖具有不同签名的虚函数

c++ - 堆摘要错误中不匹配

c - 为什么这个函数不能正确地将数组中的值乘以给定的倍数?

php - 使用 ini_set ("memory_limit", "-1")并且仍然内存不足

c++ - 如何在 Linux(和 OSX)上查询分配的内存量?

c++ - 为什么map在(switch)格外变成空的?

c++ - 如何在键是自定义对象的情况下使用 stdext::hash_map?

C - 与指针有关的语义

linux - Spreadsheet::WriteExcel set_optimization() 生成取消链接错误