创建新班级的开销

创建新班级的开销

本文介绍了创建新班级的开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如果我有一个这样定义的类:

If I have a class defined as such:

class classWithInt
{
public:
    classWithInt();
...
private:
    int someInt;
...
}

并且someIntclassWithInt中的一个也是唯一的成员变量,声明这个类的新实例比声明一个新的整数要慢多少?

and that someInt is the one and only one member variable in classWithInt, how much slower would it be to declare a new instance of this class than to just declare a new integer?

当您在类中说10个这样的整数时,该怎么办? 100?

What about when you have, say 10 such integers in the class? 100?

推荐答案

在早晨的凌晨,使用并非由醉酒的大学生编写的编译器,开销为零.至少要等到开始使用virtual函数时为止;那么您必须支付虚拟调度机制的费用.或者,如果类中没有没有数据,则在这种情况下,类仍需要占用一些空间(这又是因为每个对象在内存中必须具有唯一的地址).

With a compiler not written by drunk college students in the wee hours of the morning, the overhead is zero. At least until you start putting in virtual functions; then you must pay the cost for the virtual dispatch mechanism. Or if you have no data in the class, in which case the class is still required to take up some space (which in turn is because every object must have a unique address in memory).

函数不是对象数据布局的一部分.它们只是对象的心理概念的一部分.该函数将转换为将对象的实例作为附加参数的代码,并相应地转换对成员函数的调用以传递该对象.

Functions are not part of the data layout of the object. They are only a part of the mental concept of the object. The function is translated into code that takes an instance of the object as an additional parameter, and calls to the member function are correspondingly translated to pass the object.

数据成员的数量无关紧要.比较苹果与苹果;如果您有一个包含10个整数的类,那么它将占用与10个整数相同的空间.

The number of data members doesn't matter. Compare apples to apples; if you have a class with 10 ints in it, then it takes up the same space that 10 ints would.

无论它们是什么,分配在栈上的东西实际上都是免费的.编译器将所有局部变量的大小加起来,并一次调整堆栈指针以为其留出空间.在内存中分配空间成本,但是成本可能更多地取决于分配数量,而不是分配的空间量.

Allocating things on the stack is effectively free, no matter what they are. The compiler adds up the size of all the local variables and adjusts the stack pointer all at once to make space for them. Allocating space in memory costs, but the cost will probably depend more on the number of allocations than the amount of space allocated.

这篇关于创建新班级的开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:44