是否可以将几个对象放在一个联合内? [英] Is it possible to put several objects together inside a union?

查看:164
本文介绍了是否可以将几个对象放在一个联合内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个:

union{
    vector<int> intVec ;
    vector<float> floatVec ;
    vector<double> doubleVec ;
} ;

当然,我只使用3个向量中的一个。但是...当所有3个向量都被构造时会发生什么?

3个向量的析构函数会相互干扰吗? (因为其中3个在同一个内存地址)

Of course, I'll be using just one of the 3 vectors. But... what happens when all the 3 vectors are contructed??
Would the consructors of the 3 vectors interfere with each other?? (since the 3 of them are in the same memory address)

谢谢。

推荐答案

当前C ++标准不允许在工会内使用非POD类型。您将从 gcc

error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with constructor not allowed in union
error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with destructor not allowed in union

标准( C ++ 0x )建议无限制联盟,但向C ++添加了更多对象生命周期陷阱

New C++ standard (C++0x) proposes unrestricted unions, but it adds yet more object lifetime pitfalls to C++.

这篇关于是否可以将几个对象放在一个联合内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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