C++11 中提议的无限制联盟是什么?
我将无限制联合
视为 C++11 中提出的功能之一。谁能解释一下这背后的语义及其提供的优势吗?
I gather unrestricted unions
as one of the functionality being put forth in C++11. Can anyone please explain the semantics behind this and the advantages it provides?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
维基百科上有一个解释: http://en.wikipedia.org/wiki/C%2B%2B0x #Unrestricted_unions
在询问 C++0x 功能解释之前先搜索那里。
不受限制的工会
There is an explaination on Wikipedia : http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions
Search there first before asking about C++0x features explainations.
Unrestricted unions
它只不过是我们一直拥有的旧联合,一个一次包含一个不同类型成员的对象。
变化只是您现在可以在联合中存储非 POD 类型。但是,您将负责显式构造和销毁该成员。
来自 N3242:
在我看来,这不是一个广泛有用的功能。
It is nothing else than the old unions we have always had, an object containing one member at a time, of varying type.
The change is just that you are now allowed to store non-POD types in a union. However, you will then be responsible for explicitly constructing and destroying that member.
From N3242:
Not a widely useful feature, IMO.
它扩展联合以允许任何类型,而不仅仅是“普通旧数据”,使您能够更灵活地在同一位置存储不同类型的数据,而无需诉诸手动指针黑客技术。
为此付出的代价是你必须仔细记账。使用普通的旧数据联合分配足以更改“当前类型”,并且读取错误的类型可能会导致乱码数据,但仅此而已。对于非普通旧数据联合,您必须跟踪当前类型并手动调用正确的构造函数和析构函数来更改当前类型,并在销毁整个联合时正确清理内容。如果您尝试读取或写入 wring 类型,则可能会发生不好的事情
It expands unions to allow any type, not just "plain old data", giving you more flexibility to store different types of data in the same location without resorting to manual pointer hackery.
The price you pay for this is that you have to do some careful book keeping. With a plain old data union assignment was enough to change the "current type" and reading the wrong type was likely to result in garbled data but not much more than that. With a non plain old data union you must keep track of the current type and call the correct constructors and destructors manually to change the current type and to clean things up correctly when destroying the union as a whole. If you try to read or write the wring type bad things are likely to happen