例如,假设我有一个类Temp:
class Temp
{
public:
int function1(int foo) { return 1; }
void function2(int bar) { foobar = bar; }
private:
int foobar;
};
Run Code Online (Sandbox Code Playgroud)
当我创建Temp类的对象时,我如何计算它需要多少空间,以及它如何在内存中表示(例如| foobar | 4个字节| function1 | 8的8个字节|)
考虑:
class A
{
public:
virtual void update() = 0;
}
class B : public A
{
public:
void update() { /* stuff goes in here... */ }
private:
double a, b, c;
}
class C {
// Same kind of thing as B, but with different update function/data members
}
Run Code Online (Sandbox Code Playgroud)
我现在在做:
A * array = new A[1000];
array[0] = new B();
array[1] = new C();
//etc., etc.
Run Code Online (Sandbox Code Playgroud)
如果我调用sizeof(B),返回的大小是3个双成员所需的大小,加上虚函数指针表所需的一些开销.现在,回到我的代码,结果是'sizeof(myclass)'是32; 也就是说,我的数据成员使用24个字节,虚拟功能表使用8个字节(4个虚函数).我的问题是:有什么办法可以简化这个吗?我的程序最终会使用大量的内存,我不喜欢它的25%被虚拟函数指针吃掉的声音.
结果说12。
该函数foobar存储在内存中的什么位置?
#include <iostream>
using namespace std;
struct ABC_ {
int a;
int b;
int c;
int foobar(int a) {
return a;
}
};
int main() {
ABC_ ABC;
cout << sizeof ABC;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我正在使用std :: map,无法理解它消耗了多少内存。
我有以下地图定义:
CKey {
long x;
int y;
int z;
bool operator<(const CKey& l) const;
};
CValue {
int data1;
int data2;
}
std::map<CKey, CValue> map;
std::cout << "sizeof() = " << sizeof(map) << " Max #Elms = " << map.max_size();
Run Code Online (Sandbox Code Playgroud)
(在地图中插入元素之前或之后都没有问题)
sizeof() = 48
Max_Size = 329406144173384850
Run Code Online (Sandbox Code Playgroud)