C ++结构成员内存分配 [英] C++ struct member memory allocation

查看:96
本文介绍了C ++结构成员内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的结构:

I have a struct that looks like this:

struct rtok {
    char type;
    std::string val;
    bool term;
};

我正在编写一个简单的解释器,而这种"rtok"结构就是我表示令牌的方式.我有一个"rtoks"向量,可以迭代生成解析树.

I'm writing a simple interpreter and this "rtok" struct is how I represent a token. I have a vector of "rtoks" that I iterate through to generate the parse tree.

我的问题是,如果我的结构中有3个成员,而我只给1个成员赋值,其他成员是否还会占用内存?

My question is, if I have 3 members in my struct and I only give a value to 1 member, will the other members still take up memory?

我的意思是,如果我将"val"设置为等于"test",我的令牌将仅占用4个字节还是占6个字节? ("val"为4个字节,类型为1个字节,术语为1个字节)

What I mean is, if I set "val" equal to "test" would my token take up just 4 bytes or would it take up 6 bytes? (4 bytes for "val", 1 byte for type, 1 byte for term)

推荐答案

假定您没有其他成员或虚函数,则您的结构将始终占据sizeof(char) + sizeof(string) + sizeof(bool) + possible padding. string部分为自己分配了一块内存,它在销毁时会对其进行分配.但是,从技术上讲,此内存不是为struct分配的内存的一部分.

Assuming you don't have additional members or virtual functions, your struct will always occupy sizeof(char) + sizeof(string) + sizeof(bool) + possible padding. The string part allocates itself a chunk of memory, which it deallocates at destruction. However, this memory is not technically part of the one allocated for the struct.

因此,无论您为成员提供(或忽略)这些值是什么,该结构都将始终具有相同的大小.

So no matter of the values you give (or omit) for the members, the struct will always have the same size.

这篇关于C ++结构成员内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆