是否为每个C ++对象编译了多个成员函数? [英] Are there multiple member functions compiled for each C++ object?

查看:59
本文介绍了是否为每个C ++对象编译了多个成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当我们创建给定类类型的多个对象时,会创建成员变量的多个副本。每个对象都有一组单独的成员变量。成员函数是否也以相同的方式工作?如果我的班级有很多函数,那么成员函数会为创建的每个对象重复吗?每个创建的对象都有它自己的成员函数集吗?

I know that when we create multiple objects of a given class type, multiple copies of the member variables are created. Each object has it's separate set of member variables. Does this work the same way with member functions too? If my class has a lot of functions, do the member functions get duplicated for each object that is created? Does each created object have it's own set of the member functions?

class demo {
  public:
    int height;
    int width;

    void setheight(int height)
    {
        this->height = height;
    }

    void getArea() const
    {
        return height * width;
    }

    // 100 more member functions.
};

这只是一个证明C ++编译器观点的假设示例。实际上,这与我在项目中所做的事情有关。假设我有一个只有几个成员变量但有很多成员函数的类类型。如果我创建了该类类型的多个对象,是否会重复代码,而每个对象都有其成员函数的副本?在那种情况下,为了避免增长可执行文件,对我来说,将这些函数声明为将对象作为参数的常规独立全局函数更好吗?

This is just a hypothetical example to prove a point about the C++ compiler. Actually this is related to what I'm doing in my project. Let's suppose I have a class type with only a few member variables but lots and lots of member functions. If I create multiple objects of that class type, will I have duplication of code, with each object having it's own copy of the member function? In that case, would it be better for me to declare the functions just as regular stand alone global functions which take the object as a parameter instead, in order to avoid growing the executable?

推荐答案

这只是一个实现细节(该标准没有强制要求对此进行任何特别说明),但是几乎所有实现类方法实际上都是常规的语法糖,是免费的函数将 this 作为隐藏参数 1 。 IOW,您建议的优化是编译器已经完成的工作。

This is just an implementation detail (the standard doesn't mandate anything particular about it), but on pretty much any implementation class methods are essentially syntactic sugar for "regular", free functions taking this as a hidden parameter1. IOW, your proposed optimization is what the compiler already does.

虚拟方法涉及一些额外的机制,因为每个虚拟方法通常会花费 vtable的vtable中的一个插槽类(及其所有派生类),但同样,它是O(1)的空间成本,而不是实例数的O(n)。

There's some extra machinery involved for virtual methods, as every virtual method generally "costs" one slot into the vtable of the class (and all its derived classes), but again, it's a O(1) space cost, not O(n) in the number of instances.


  1. 在某些实现中,调用约定也有所不同,例如在x86 VC ++上,方法在 ecx 中接收到 this 而不是在堆栈上接收,因为如果它是具有这个作为第一个参数,但这与我们的讨论无关。

  1. On some implementations there's also a difference in calling convention, e.g. on x86 VC++ methods receive this in ecx instead than on the stack as it would be if it were a free function with this as first parameter, but that's irrelevant for our discussion.

这篇关于是否为每个C ++对象编译了多个成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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