C++ 中 class 对象的大小
Size of class object in C++
class 对象的大小显示为 12 的依据是什么?
class testvector
{
public : vector<int> test;
};
int main()
{
testvector otestvector;
cout<<"size :"<<sizeof(otestvector)<<"\n";
cout<<"size of int :"<<sizeof(int);
}
输出:
size :12
size of int :4
这样想。假设标准 C++ 库没有 vector
class。你决定拥有一个是个好主意。
你可能至少会想出这样的东西。 (免责声明:C++ 的实际向量 class 比 远 复杂)
template <class T>
class vector
{
T* items; // array of items
size_t length; // number of items inserted
size_t capacity; // how many items we've allocated
public:
void push_back(const T& item) {
if (length >= capacity) {
grow(length * 2); // double capacity
}
items[length] = item;
length++;
}
...
};
让我们在 32 位系统上分解我的简单向量 class 的一个实例:
sizeof(items) == 4 // pointers are 4 bytes on 32-bit systems
sizeof(length) == 4; // since size_t is typically a long, it's 32-bits as well
sizeof(capacity) == 4; // same as above
所以刚开始有 12 个字节的成员变量。因此 sizeof(vector<T>) == 12
作为我的简单示例。 T
实际上是什么类型并不重要。 sizeof() 运算符只考虑成员变量,而不是与每个变量相关联的任何堆分配。
以上只是一个粗略的例子。实际向量 class 具有更复杂的结构、对自定义分配器的支持以及其他针对高效迭代、插入和删除的优化。因此,class.
中可能有更多成员变量
所以至少,我的最小示例已经有 12 个字节长了。在 64 位编译器上可能是 24 个字节,因为 sizeof(pointer) 和 sizeof(size_t) 通常在 64 位上加倍。
class 对象的大小显示为 12 的依据是什么?
class testvector
{
public : vector<int> test;
};
int main()
{
testvector otestvector;
cout<<"size :"<<sizeof(otestvector)<<"\n";
cout<<"size of int :"<<sizeof(int);
}
输出:
size :12
size of int :4
这样想。假设标准 C++ 库没有 vector
class。你决定拥有一个是个好主意。
你可能至少会想出这样的东西。 (免责声明:C++ 的实际向量 class 比 远 复杂)
template <class T>
class vector
{
T* items; // array of items
size_t length; // number of items inserted
size_t capacity; // how many items we've allocated
public:
void push_back(const T& item) {
if (length >= capacity) {
grow(length * 2); // double capacity
}
items[length] = item;
length++;
}
...
};
让我们在 32 位系统上分解我的简单向量 class 的一个实例:
sizeof(items) == 4 // pointers are 4 bytes on 32-bit systems
sizeof(length) == 4; // since size_t is typically a long, it's 32-bits as well
sizeof(capacity) == 4; // same as above
所以刚开始有 12 个字节的成员变量。因此 sizeof(vector<T>) == 12
作为我的简单示例。 T
实际上是什么类型并不重要。 sizeof() 运算符只考虑成员变量,而不是与每个变量相关联的任何堆分配。
以上只是一个粗略的例子。实际向量 class 具有更复杂的结构、对自定义分配器的支持以及其他针对高效迭代、插入和删除的优化。因此,class.
中可能有更多成员变量所以至少,我的最小示例已经有 12 个字节长了。在 64 位编译器上可能是 24 个字节,因为 sizeof(pointer) 和 sizeof(size_t) 通常在 64 位上加倍。