https://www.cnblogs.com/fengty90/p/3768840.html
当多个数据需要共享内存或者多个数据每次只取其一时,可以利用联合体(union)。
#include<iostream> using namespace std; union U1 { int n; char s[11]; double d; }; union U2 { int n; char s[5]; double d; }; int main() { U1 u1; U2 u2; cout<<sizeof(u1)<<‘\t‘<<sizeof(u2)<<endl; cout<<"u1各数据地址:\n"<<&u1<<‘\t‘<<&u1.d<<‘\t‘<<&u1.s<<‘\t‘<<&u1.n<<endl; cout<<"u2各数据地址:\n"<<&u2<<‘\t‘<<&u2.d<<‘\t‘<<&u2.s<<‘\t‘<<&u2.n<<endl; }
输出:
16 8 u1各数据地址: 0x74fe10 0x74fe10 0x74fe10 0x74fe10 u2各数据地址: 0x74fe08 0x74fe08 0x74fe08 0x74fe08
可以发现u1和u2对象的地址,就是首个元素的地址,并且所有元素的地址都相同!
SGI STL的二级空间配置器的free list用到了它。
https://www.cnblogs.com/fengty90/p/3768840.html
原文:https://www.cnblogs.com/BlueBlueSea/p/14856430.html