如果我有这个怎么办:
union{
vector<int> intVec ;
vector<float> floatVec ;
vector<double> doubleVec ;
} ;
Run Code Online (Sandbox Code Playgroud)
当然,我将只使用3个向量中的一个.但是......当所有3个载体都被构造时会发生什么?
3个向量的构成器会相互干扰吗?(因为它们中的3个在相同的内存地址中)
谢谢.
Ale*_*x B 16
当前的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
Run Code Online (Sandbox Code Playgroud)
新的C++标准(C++ 0x)提出了不受限制的联合,但它为C++ 增加了更多的对象生命周期陷阱.
您不能拥有包含非POD类类型的联合.您的示例将无法编译.
您可以使用boost::variantC联盟的安全替代方案.请参阅boost.org上的文档.但是,您可能会重新考虑您的设计并使用多态.当然,取决于你想要完成的事情.
| 归档时间: |
|
| 查看次数: |
6670 次 |
| 最近记录: |