![]() |
#2
Jonny02012020-10-11 13:21
当 union 内部存在具有 non-trivial 构造函数的成员, union 的构造函数会被编译器指定为被删除的函数
union 的构造和解构都比较复杂, 需要使用一个标记, 标记哪个成员被使用, 如果是非 POD 类型的话, 是需要明确建构和解构的 ![]() class Union { private: enum {STRING, INT, CHAR, DOUBLE} token; union { std::string str; int i; char c; double d; }; private: void copy(const Union &rhs) { switch(rhs.token) { case STRING: new (&this->str) std::string(rhs.str); break; case INT: this->i = rhs.i; break; case CHAR: this->c = rhs.c; break; default: this->d = rhs.d; break; } } public: constexpr Union() noexcept : token {INT}, i {} {} Union(const Union &rhs) : token {rhs.token} { this->copy(rhs); } Union &operator=(const Union &rhs) { if(this->token == STRING and rhs.token not_eq STRING) { this->str.~string(); }else if(this->token == STRING and rhs.token == STRING) { this->str = rhs.str; return *this; } this->copy(rhs); this->token = rhs.token; return *this; } Union &operator=(std::string str) { if(this->token == STRING) { this->str = std::move(str); return *this; } new (&this->str) std::string(std::move(str)); this->token = STRING; return *this; } Union &operator=(char c) { if(this->token == STRING) { this->str.~string(); } this->c = c; this->token = CHAR; return *this; } //和 Union &operator=(char); 一样 Union &operator=(int i); Union &operator=(double d); }; |
typedef struct
{
int a;
String str_a;
}Config_AA;
typedef struct
{
int b;
String str_b;
}Config_BB;
typedef struct
{
int c;
String str_c;
}Config_CC;
typedef struct
{
Config_AA m_AA;
Config_BB m_BB;
Config_CC m_CC;
}Config;
Config m_Config;
{
int a;
String str_a;
}Config_AA;
typedef struct
{
int b;
String str_b;
}Config_BB;
typedef struct
{
int c;
String str_c;
}Config_CC;
typedef struct
{
Config_AA m_AA;
Config_BB m_BB;
Config_CC m_CC;
}Config;
Config m_Config;
定义一个全局变量Config m_Config;其中包含类string。
如果变成
typedef struct
{
union{
Config_AA m_AA;
Config_BB m_BB;
Config_CC m_CC;
}m_data;
}Config;
{
union{
Config_AA m_AA;
Config_BB m_BB;
Config_CC m_CC;
}m_data;
}Config;
会因为union包含了string构造函数,导致union无法初始化内存而报错。
那么为什么使用结构体就不会报错,使用malloc(mun*sizeof(m_Config));的时候分配了多大的空间?
如果包含有类的绝结构体不能使用malloc分配空间,应该怎么分配空间初始化?
如何把c语言习惯上的全局变量嵌套形式的结构体使用C++的全局类的形式表示?