我在想:他们说如果你手动调用析构函数--你做错了什么。但情况总是这样吗?有什么反例吗?需要手动调用它,或者很难/不可能/不切实际地避免它的情况?
发布于 2018-06-30 17:15:15
发现了另一个必须手动调用析构函数的示例。假设您已经实现了一个类似variant的类,它包含以下几种类型的数据之一:
struct Variant {
union {
std::string str;
int num;
bool b;
};
enum Type { Str, Int, Bool } type;
};如果Variant实例持有一个std::string,而您现在为联合分配了一个不同的类型,则必须首先析构该std::string。The compiler will not do that automatically。
https://stackoverflow.com/questions/14187006
复制相似问题