在C中,联合只是如何解释存储在给定位置的数据的问题.数据是被动的.
在C中,工会可以拥有不同类别的成员.类对象不仅具有数据,还具有行为.当您依赖此(可访问)行为(甚至可能无法访问私有和受保护的成员)时,必须确保对象从其构造到其销毁保持一致.活动成员的概念完全出于此目的:确保对象生命周期是一致的.
更长的解释
想象一下以下的联盟:
union U { string s; int i; // due to string,I need to define constructor and destructor U (string s) : s(s) { cout << "s is active"<<endl;} U (int i) : i(i) { cout << "i is active"<<endl;} U() : s() { cout << "s is active by default" <<endl; } ~U() { cout << "delete... but what ?"<<endl; }};
现在假设我初始化它:
U u("hello");
活跃的成员就在那一刻.我现在可以毫无风险地使用这个活跃的memeber:
u.s += ",world"; cout << u.s <<endl;
在更改活动成员之前,我必须确保成员的生命周期结束(根据C标准的要求).如果我忘了这个,例如使用另一个成员:
u.i=0; // ouch!!! this is not the active member : what happens to the string ?
然后我有未定义的行为(在实践中,s现在已损坏,并且不再可能恢复存储字符的内存).你也可以想象相反的情况.假设活动成员是i,我现在想要使用该字符串:
u.s="goodbye"; // thinks that s is an active valID string which is no longer the case
在这里,编译器确认我知道s是活动成员.但由于s不是正确初始化的字符串,执行复制 *** 作符也会导致未定义的行为.
Demo of what you should not do
怎么做对了?
该标准解释了它:
If M has a non-trivial destructor and N has a non-trivial constructor
(for instance,if they declare or inherit virtual functions),the
active member of u can be safely switched from m to n using the
destructor and placement new-Expression as follows:06005
所以在我们讨厌的例子中,以下内容可行:
u.s.~string(); // properly end the life of su.i=0; // this is Now the active member // no need to end life of an int,as it has a trivial destructor new (&u.s) string("goodbye"); // placement new cout << u.s <<endl;
Demo of how to (almost) do it right
总结以上是内存溢出为你收集整理的c – 工会活跃成员背后的理由全部内容,希望文章能够帮你解决c – 工会活跃成员背后的理由所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)