Are there multiple member functions compiled for e

2019-07-30 01:37发布

问题:

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.
};

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?

回答1:

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.

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. 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.