【问题标题】:Are class/struct functions stored in an object?类/结构函数是否存储在对象中?
【发布时间】:2013-09-17 02:09:15
【问题描述】:

假设:

struct A {
    int a;
    int b;
};

struct B {
    int a;
    int b;

    int func() {
        return this->a + this->b;
    }
};

B 的实例是否包含指向 func 的指针?

用代码说明这个问题:

A a; // first 4 bytes are for `int a`, second 4 bytes are for `int b`
B b: // ditto, but is there an extra word for a pointer to function `func`?

【问题讨论】:

    标签: c++ class object storage


    【解决方案1】:

    没有。 ab 的大小完全相同(b 不存储指向 func 的指针)。

    C++ 中的类函数与对象本身没有链接(指向),它们只是作为任何其他函数存储。当你调用一个类函数时,你只是在调用一个普通函数(你不是从一个指针调用它)。这就是为什么在 C++ 中执行 b.func = another_func; 之类的操作是非法的。

    用代码来说明这一点:

    /////////
    // C++
    /////////
    struct B {
        int a;
        int b;
    
        int func() {
            return this->a + this->b;
        }
    };
    
    B b;
    b.func();
    
    
    //////////////////////////////
    // Example compile output if it was compiled to C (not actual compile output!)
    // i.e. this C code will do the equivalent of the C++ code above
    //////////////////////////////
    struct B {
        int a;
        int b;
    };
    
    int B_func(struct B* this) {
        return this->a + this->b;
    }
    
    B b;
    B_func(&b);
    
    // This should illustrate why it is impossible to do this in C++:
    // b.func = another_func;
    

    【讨论】:

    • 您可能想补充一点,virtual 函数有点不同。
    • 成员函数并不完全是“任何正常函数”。他们确实隐藏了this 参数。实际上,您的 C 示例正是 C++ 编译器将执行的操作...也许您的措辞让我感到困惑,而您的意思实际上正是如此。
    • @PetrBudnik 是的,我的措辞不是最好的:P 基本上,我的意思是,当您调用成员函数时,您只是正常调用它,而不是通过存储在内部的指针对象。
    【解决方案2】:

    C++ 函数实际上只是(可能)将指向对象的隐藏指针作为第一个参数的函数。通过name mangling实现唯一性。

    除非函数是虚函数;具有一个或多个虚函数的类具有“虚函数表”(vtable),并且这些类的实例具有指向其特定于实例的 vtable 的指针的开销。 vtable 是在对象之前还是之后取决于编译器/实现。

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多