谈结构体中std::string所占的空间

#include <string>

#include <iostream>

 

 

struct  test

{

int iID;

int iType;

std::string strName;

int iLevel;

 

 

test()

{

iID = 2;

iType = 2;

iLevel = 2;

strName = "Hello, world";

}

};

 

 

void Output(test& stTest)

{

char * pID = (char*)(&stTest);

 

cout << (int)(*pID) << endl;

 

cout << (int)(*(pID+sizeof(int))) << endl;

 

 

std::string *pName = (std::string *)(pID+sizeof(int) + sizeof(int));

 

cout << *pName << endl;

 

*pName = "hello";

 

cout << (int)(*(pID+sizeof(int) + sizeof(int)+sizeof(std::string))) << endl;

 

}

 

 

int main()

{

test stTest;

 

cout << sizeof(stTest) << endl;

 

Output(stTest);

Output(stTest);

}

 

结果如下:

 

40

2

2

Hello, world

2

2

2

hello

2

 

通过实验标明,string在结构体中只占用 sizeof(std::string)个字节,不会因为其中的内容长短而有所变化,

可见其中的内容是另一块存储区,本地只保存一个地址作为索引。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值