[英]Does it matter which element I delete in a union
I am writing a translator and for that, I want to create a class Verb.我正在写一个翻译器,为此,我想创建一个类动词。 this class should only save the complete cunjugation when it is irregular because it would produce large lists, taking much memory.这个类应该只在不规则时保存完整的 cunjugation,因为它会产生大列表,占用大量内存。 So here's my code:所以这是我的代码:
#include "string.h"
struct Irregular{
std::string present;
std::string simplepast;
std::string pastparticiple;
}
union Verbform{
Irregular* irregular;
std::string* regular;
Verbform(Irregular irreg){irregular=new Irregular(irreg);}
Verbform(std::string s){regular=new std::string(s);
~Verbbform(){delete regular;} //here is my problem
}
class Verb{
public:
//some public functions
private:
Verbform verbform;
//some other things;
}
When I do it like this and I initialize it with an irreglar verb, does he delete the complete irregular verb or only the first string?当我这样做并用一个不规则动词初始化它时,他是删除完整的不规则动词还是只删除第一个字符串?
When I do it like this: ~Verbform(){delete irregular;}
and I initialize it with a normal string, does he deletes more than I want him to delete?当我这样做时: ~Verbform(){delete irregular;}
并且我用普通字符串初始化它时,他删除的次数是否超过了我希望他删除的次数?
delete irregular
calls the ~Irregular()
destructor, which then calls the std::string::~string()
destructor 3 times. delete irregular
调用~Irregular()
析构函数,然后调用std::string::~string()
析构函数 3 次。 Calling this when irregular
is n not the active union member is undefined behavior .当irregular
不是活动联合成员时调用此方法是未定义行为。
delete regular
calls the std::string::~string()
destructor 1 time. delete regular
调用std::string::~string()
析构函数 1 次。 Calling this when regular
is not the active union member is undefined behavior .当regular
不是活动的联合成员时调用它是未定义的行为。
You need to keep track of which member of the union is active so you can call the appropriate destructor, eg:您需要跟踪联合的哪个成员处于活动状态,以便您可以调用适当的析构函数,例如:
enum Verbform_type { vtIrregular, vtRegular };
union Verbform_data {
Irregular* irregular;
std::string* regular;
};
struct Verbform {
Verbform_type type;
Verbform_data data;
Verbform(Irregular irreg) {
type = vtIrregular;
data.irregular = new Irregular(irreg);
}
Verbform(std::string reg) {
type = vtRegular;
data.regular = new std::string(reg);
}
~Verbform() {
switch (type) {
case vtIrregular:
delete data.irregular;
break;
case vtRegular:
delete data.regular;
break;
}
}
}
Also, don't forget to follow the Rule of 3/5/0 by adding copy/move constructors and copy/move assignment operators.另外,不要忘记通过添加复制/移动构造函数和复制/移动赋值运算符来遵循3/5/0 规则。
Otherwise, you should just get rid of your Verbform
struct altogether and use std::variant
instead.否则,您应该完全摆脱Verbform
结构并使用std::variant
代替。 Let it handle all of these details natively for you.让它为您处理所有这些细节。
using Verbform = std::variant<Irregular, std::string>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.