为什么编译器不允许std :: string里面的union? [英] Why compiler doesn't allow std::string inside union?

查看:967
本文介绍了为什么编译器不允许std :: string里面的union?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Union内使用字符串。
如果我写如下

i want to use string inside Union. if i write as below

union U
{
   int i;
   float f;
   string s;
};

编译器给出错误说U :: S有复制构造函数。

Compiler gives error saying U::S has copy constructor.

我阅读了一些其他的帖子,以解决这个问题的替代方法。
但是我想知道为什么编译器不允许这个在第一次?

I read some other post for alternate ways for solving this issue. But i want to know why compiler doesn't allow this in the first place?

编辑:@KennyTM:在任何联合,如果成员初始化其他将有垃圾值,如果没有初始化所有将有垃圾值。我认为,标记联合只是提供一些舒适来访问有效的值从联盟。
你的问题:你或者编译器如何为上面的union写一个复制构造函数而没有额外的信息?
sizeof(string)给出4个字节。基于此,编译器可以比较其他成员大小并分配最大分配(在我们的示例中为4字节)。内部字符串长度无关紧要,因为它将存储在单独的位置。让字符串为任意长度。所有的联盟必须知道是调用字符串类复制构造函数与字符串参数。无论哪种方式,编译器发现在正常情况下必须调用复制构造函数,即使在字符串在Union内部时,也要遵循类似的方法。所以我认为编译器可以做,分配4字节。然后如果任何字符串被分配给s,则string类将使用它自己的分配器来处理该字符串的分配和复制。因此,没有内存损坏的机会。

@KennyTM: In any union, if member is initialized others will have garbage values, if none is initialized all will have garbage values. I think, tagged union just provides some comfort to access valid values from Union. Your question: how do you or the compiler write a copy constructor for the union above without extra information? sizeof(string) gives 4 bytes. Based on this, compiler can compare other members sizes and allocate largest allocation(4bytes in our example). Internal string length doesn't matter because it will be stored in a seperate location. Let the string be of any length. All that Union has to know is invoking string class copy constructor with string parameter. In whichever way compiler finds that copy constructor has to be invoked in normal case, similar method as to be followed even when string is inside Union. So i am thinking compiler could do like, allocate 4 bytes. Then if any string is assigned to s, then string class will take care of allocation and copying of that string using its own allocator. So there is no chance of memory corruption as well.

在编译器联合开发时,字符串是否不存在?
所以答案还不清楚。
在这个网站的新加盟,如果有什么不对,请原谅。

Is string not existed at the time of Union developement in compiler ? So the answer is not clear to me still. Am a new joinee in this site, if anything wrong, pls excuse me.

推荐答案

想想。编译器如何知道什么类型在联合中?

Think about it. How does the compiler know what type is in the union?

它不是。联盟的基本运作本质上是一种按位。对联合中包含的值的操作只有在每个类型基本上都被垃圾填充时才是安全的。 std :: string 不能,因为这将导致内存损坏。使用 boost :: variant boost :: any

It doesn't. The fundamental operation of a union is essentially a bitwise cast. Operations on values contained within unions are only safe when each type can essentially be filled with garbage. std::string can't, because that would result in memory corruption. Use boost::variant or boost::any.

这篇关于为什么编译器不允许std :: string里面的union?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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