为什么成员函数地址与自由函数相距如此远? [英] Why member function address are so far away from free functions?

查看:113
本文介绍了为什么成员函数地址与自由函数相距如此远?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以该示例为例: 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个字节.

I see the address of the member function is 0x7018400100000000000, which is understandable because member functions pointers have 16 bytes while free function as 0x100401080 have only 8 bytes.

但是,为什么成员函数地址0x7018400100000000000与自由函数地址0x100401080如此远?即|0x7018400100000000000 - 0x100401080| = 0x70184000FFEFFBFEF80?

However, why the member function address 0x7018400100000000000 is so far away from free function address 0x100401080? i.e., |0x7018400100000000000 - 0x100401080| = 0x70184000FFEFFBFEF80?

为什么它不更靠近,即类似0x100401...而不是0x701840...?还是我打印的成员函数地址错误?

Why it is not closer i.e., something like 0x100401... instead of 0x701840...? Or I am printing the member function address wrong?

推荐答案

您的体系结构是低端的.地址的低字节在p的第一个字节中,因此您的地址被向后打印.

Your architecture is little-endian. The low byte of the address is in the first byte of p, so your address is being printed out backwards.

这篇关于为什么成员函数地址与自由函数相距如此远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆