简体   繁体   English

什么时候为C ++中的类的成员函数分配了内存空间?

[英]When is the memory space for a member function of a class in C++ allocated?

While reading I read these conflicting statements on the memory allocation of member functions of Classes in C++. 在阅读时,我阅读了有关C ++中类成员函数的内存分配的这些冲突语句。 One source said the space is allocated for the member functions as on need basis from the memory stack. 一位消息人士说,根据需要,从内存堆栈中为成员函数分配了空间。 While the other said the space is allocated when the first object of that class is created. 另一个表示创建该类的第一个对象时已分配空间。

On the other hand, I had the notion that space for member functions are allocated during compilation or beginning of runtime itself, and the function code is then used by all the objects of that class. 另一方面,我的想法是,成员函数的空间在编译或运行时本身开始时分配,然后该类的所有对象都使用函数代码。

Could someone please clarify and elaborate? 有人可以澄清和阐述吗? Thanks. 谢谢。

What memory? 什么记忆? There's memory needed to store the actual (compiled code) and memory for the variables (Data). 需要存储实际(已编译的代码)的存储器和变量(数据)的存储器。 Both your answers are therefore correct. 因此,您的两个答案都是正确的。

Member functions does not contribute to the memory usage of class objects except that if a class has virtual functions then it keeps a pointer to the table of virtual functions. 成员函数不会增加类对象的内存使用率,除非类具有虚函数,然后它会保留指向虚函数表的指针。

As any function a member function can have no definition if there is no access to the function in the program. 作为任何函数,如果无法在程序中访问该函数,则成员函数将没有定义。 Otherwise the linker will issue an error that the reference to the function is undefined. 否则,链接器将发出一个错误,指出对该函数的引用未定义。

The compiler generates code for member functions the same way as for non-member functions. 编译器为成员函数生成代码的方式与为非成员函数生成代码的方式相同。 So if there is a definition of a member function when the compiler will generate the corresponding code. 因此,如果存在成员函数的定义,则编译器将生成相应的代码。

I think that you meant member functions of template classes then they indeed will be instantiated if they are used. 我认为您的意思是模板类的成员函数,如果使用它们,它们的确会实例化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM