以前,C语言写结构体时。结构体成员都是基本类型,比如int、char、double之类的,最多也就里边再套一个结构体成员,但它们都有一个特点。它们的大小是固定的,我不会有这样的担心。但是,我接触到string、vector这些类类型时,根据它们的特性:它们能动态扩充,就是你来多少内容,我都能存的下!
然后,我就想:那它们的变量大小是不是也扩充了,那是不是也导致所处的结构体的变量的大小也改变了呢?
因此,我查了下书。找到了答案:总结一下,简单来说就是,这些动态可变更存储长度的类都是使用指针,附加动态申请内存实现的。而动态申请的内存本身并不包含在对象的本身大小上面,在对象中保存一个指针,它能够找到动态申请的内存的地址。所以,你不管动态申请多少内存,它对象中的一个指针总能找得到你,它指针的大小不会发生改变。也就是说,它所在的结构体变量的大小也是不会改变的!
我也写了一个小程序检查了一下,大家可以通过运行结果看到结构体变量的大小并没有改变!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef struct Vec
{
vector<int> int_vec;
}Int_vec;
typedef struct Str
{
string str;
}Str_string;
int main(void)
{
Int_vec myInt;
Str_string myString;
cout << "空的 myInt 大小:" << sizeof(myInt) << endl << endl;
cout << "空的 myString 大小:" << sizeof(myString) << endl << endl;
for (int i = 0; i < 10;i++)
{
myInt.int_vec.push_back(i);
}
myString.str = "student";
cout << "有十个元素的 myInt 大小:" << sizeof(myInt) << endl << endl;
cout << "有字符串内容的 myString 大小:" << sizeof(myString) << endl << endl;
return 0;
}