开发者

Difference between static method and non static function in memory

As I understand, each instance of a class has its own member variables in memory, so that it can store different values for different objects. However, it is not the same for member functions. Member functions are reused across objects of a class, so it only has one address开发者_运维问答 with one block of memory to refer when needed by all objects.

Static function is made to access static members. However, static function also exists only one during the lifetime of its application. Aside from being the static accessor, at low level it is not different with normal class functions, isn't it? Or maybe I'm wrong, that each class has its own functions?


Non-static functions accept additional parameter, this, which is the pointer to the class instance with the instance-specific variables.

Static functions don't have this parameter (thus you can't use this in a static function and can only access static data members).


This differs from language to language, but in C or C++03 functions generally map on assembly functions; that is they exist once in memory (whether free functions, class functions or class static functions) and take arguments as parameters, including a this pointer for member functions that is implicit.

In C++11, lambda functions introduce a novelty: each instance of the so-called function will carry some state. From an implementation point of view, it therefore means that a "regular" function needs be created and it is associated to an anonymous bundle of data (if necessary). The function need not be duplicated each time the lambda is created, but the data does. One helpful figure is to remember that lambdas (in C++) replace function objects (or predicate objects): they are just syntactic sugar, the implementation is similar.


The only difference between static and member functions is that member functions always have the this pointer passed in automatically.


simply if it is referred, static functions creates a single set of memory for itself and are meant for static data-members which are generally not changeable. But non-static functions creates separate set of memories for each instances and are meant for both non-static and static data-members. If u require stable output go for static and if u require the alternate go for the non-static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜