mas*_*asT 5 c++ destructor unions
union是用户定义的数据或类类型,在任何给定时间,它只包含其成员列表中的一个对象.假设需要动态分配所有可能的候选成员.对于Eg.
// Union Destructor
#include <string>
using namespace std;
union Person
{
private:
char* szName;
char* szJobTitle;
public:
Person() : szName (nullptr), szJobTitle (nullptr) {}
Person (const string& strName, const string& strJob)
{
szName = new char[strName.size()];
strcpy (szName, strName.c_str());
szJobTitle = new char [strJob.size()];
strcpy (szJobTitle, strJob.c_str()); // obvious, both fields points at same location i.e. szJobTitle
}
~Person() // Visual Studio 2010 shows that both szName and szJobTitle
{ // points to same location.
if (szName) {
delete[] szName; // Program crashes here.
szName = nullptr; // to avoid deleting already deleted location(!)
}
if (szJobTitle)
delete[] szJobTitle;
}
};
int main()
{
Person you ("your_name", "your_jobTitle");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序在~Person中的第一个删除语句中崩溃(当szName包含有效的内存位置时,为什么?).
析构函数的正确实现是什么?
同样的方法,如果我的类包含一个union成员,如何破坏一个类对象(如何为类包含一个Union的wrtie析构函数)?
| 归档时间: |
|
| 查看次数: |
3897 次 |
| 最近记录: |