Memory static function vs member function
class A (say), having all static member functions only class B(say) having only member functions
If i create 1000 instances of class A. As the class contains only static member functions, the memory do not increase even if there are 1 instance or 1000 instances.
However, for class B. If i create 1000 instances, will there be an increase of memory (even the slightest, may be a pointer for each object pointing to set of member functions) ?
If no, then how does the compiler keep tracks of member function information for a particular object ?
For starters, you might try outputting sizeof(A)
and sizeof(B)
. But several things to keep in mind:
Regardless of the number or types of members, C++ forbids a class to have a size of 0, so static members or not, each instance of A
will take some memory; and
The resolution of non-virtual functions is done entirely at compile time, so there is no need for the compiler to add anything to the class for it. (Virtual functions will typically add the size of one pointer to the class, regardless of how many virtual functions your class has.)
Will there be an increase of memory (even the slightest, may be a pointer for each object pointing to set of member functions)?
NO.
Non virtual Member functions do not contribute towards size of objects of a class.
However, presence of a virtual member function will typically increase the size of an class object.
Note that the latter is purely implementation specific detail but Since all known compilers implement the virtual mechanism using v-table
and v-ptr
, it is reasonable to assume that almost all compilers will show the same behavior of adding a v-ptr
to every object of that polymorphic class thus increasing size of the class object by size equivalent to that of v-ptr
.
If we're just talking about member functions, the imprint will be the same. A member function does not take up more memory the more times the class it is contained within is instantiated (as the this
pointer is passed to it). Only the data members of the class are going to take up more memory with each class instantiation as they are unique to each instance of the class.
So to answer your second question, it keeps "track" by the user of the this
pointer which is passed when calling a non-static member function of a class.
Things get a bit more complicated with virtual methods, but your question has not covered that particular idiom.
链接地址: http://www.djcxy.com/p/17300.html上一篇: 通过传入的指针访问静态方法内的非静态成员
下一篇: 内存静态函数与成员函数