包含std :: string的memset结构 [英] memset structure with std::string contained

查看:95
本文介绍了包含std :: string的memset结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个庞大的结构,其中整个内容是标量变量,枚举和标量数组(基于堆栈),除了一个std :: string变量。

I have a massive structure where the entire contents is scalar variables, enumerations, and arrays of scalars (stack-based) with the exception of one std::string variable.

现在,这里是我的问题...

Now, here's my question...

我可以将结构的内存设置为0的整个大小(就像我想,如果它只是所有的标量)是不是可能与std :: string在那里?我不知道什么memset会对它的内部表示。

Can I memset the structure to 0 for its whole size (like I would if it was simply all scalars), or is that not possible with the std::string being in there? I'm not sure what memset would do to its internal representation.

如果你要说的好/坏,请解释一下为什么 - 我想知道为什么是这样的:)

And if you're going to say its good/bad please explain why - I'd like to know why it is the way it is :)

推荐答案

不,你不会,它会覆盖字符串的内部状态,使坏事情发生。你可以把所有的POD东西包装在一个单独的结构体中,并把它放在你当前的结构体中,这样你就可以记住,让字符串默认构造。

No, you cant, it would overwrite the internal state of the string and make bad things happen. You could wrap all the POD stuff in a seperate struct and put that in your current one, that way you could memset that and let the string default construct.

编辑:为了澄清,该字符串几乎肯定会存储一个指向存储分配的内存的指针。字符串的构造函数将永远运行之前你可以memset它(即使你在你的类型的构造函数中的memset this ,字符串构造函数将首先运行)。所以你会覆盖这个指针值,而不是指向它的存储,它将指向NULL,或一些其他几乎肯定无效的值。

Just to clarify, the string will almost certainly be storing a pointer to the memory its allocated for storage. The string's constructor will always have run before you can memset it (even if you memset this in the constructor of your type, the string constructor would run first). So you would be overwriting this pointer value, and instead of pointing to its storage, it would a pointer to NULL, or some other almost definitely invalid value.

这篇关于包含std :: string的memset结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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