指向成员函数的指针的大小像疯了一样变化 [英] Size of pointer to member function varies like crazy

查看:43
本文介绍了指向成员函数的指针的大小像疯了一样变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到了一个非常微妙的问题.得到了一个用 MS VS 2013 c++ 编译器编译的类,对于 32 位平台有 4 个字节的大小.函数指针的大小为 4 个字节.但是当这个类用同一个编译器编译但包含在不同的项目中生成库时,也是针对 32 位平台的,那么这个类的 *m_Function 指针占用了 16 个字节!当然,当我从主项目实例化这个类时,它认为这个类占用了 4 个字节并分配了这个内存大小,而实际上它占用了 16 个字节并导致内存溢出.

Got a really subtle problem. Got a class that compiled with MS VS 2013 c++ compiler, for 32 bit platform has the size of 4 bytes. The function pointer has sizeof 4 bytes. But when this class is compiled with this same compiler but included into different project to produce library, also targeted fo 32 bit platform, then the class has the *m_Function pointer occupy 16 bytes! Of course, when I'm instantiating this class from main project it thinks that class occupies 4 bytes and allocates this very memory size, while in reality it occupies 16 bytes and that causes memory overruns.

 class CC1
    {
    public:
        CC1();

        void (CC1:: *m_Function) ();
    };

我知道指向成员函数的指针的大小可能会有所不同.但问题是 - 哪个编译器设置控制这个?我不在乎它是 4 字节还是 16 字节——只需要它们是相同的.两个项目的结构成员对齐设置相同./vmm/vmg 选项?两个项目的编译器设置中都没有提及它们.

I know that the size of pointer-to-member function can vary. But the qustion is - which compiler setting controls this? I don't care is it 4 or 16 bytes - just need them to be the same. Struct member alignment settings are the same for both projects. /vmm /vmg options? No mention of them in compiler settings in both projects.

顺便说一下,我尝试为 x64 目标构建,在这种情况下 sizeof *m_Function 总是 8 个字节,来自 main 和 libray 项目.

By the way, I tried building for x64 target and in this case sizeof *m_Function is always 8 bytes, from main and libray project.

谢谢.

推荐答案

见这里用于/vm 选项的文档页面

如果您使用 '/vmg' 编译器选项,则指向成员函数的指针将始终为 16 字节,因为您实际上是在告诉编译器它可能事先不知道大小,因此必须假设最坏的情况(虚拟继承!).

If you use the '/vmg' compiler option then pointer-to-member function will always be 16 bytes as you're effectively telling the compiler that it may not know the size beforehand and so has to assume the worst (virtual inheritance!).

如果你使用'/vmb',那么编译器在使用之前必须知道结构的继承模式,这样才能使用最有效的方法——在简单继承的情况下,这是4个字节.

If you use '/vmb' then the compiler must know about the inheritance pattern for the struct before use and so can use the most efficient method - in the case of simple inheritance this is 4 bytes.

很可能在某些项目中,您设置了/vmg"(这使类为 16 个字节),而在其他项目中则没有(使类为 4 个字节).

Its likely that in some projects you've got '/vmg' set (which makes the class 16 bytes) and in others you dont (which makes the class 4 bytes).

/vmb 是隐式默认值 - 检查您的编译器命令行中的库,其中/vmg 的此类为 16 字节

/vmb is the implicit default - check your compiler command line for the libraries where this class is 16 bytes for /vmg

这篇关于指向成员函数的指针的大小像疯了一样变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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