c++ - 如何手动删除类的实例?

标签 c++ class instance destructor kill

如何手动删除类的实例?

例子:

#include <iostream>
#include <cstring>

class Cheese {
private:
    string brand;
    float cost;
public:
    Cheese(); // Default constructor
    Cheese(string brand, float cost); // Parametrized constructor
    Cheese(const Cheese & rhs); // Copy construtor
    ~Cheese(); // Destructor
    // etc... other useful stuff follows
}

int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese swiss("Jarlsberg", 4.99);

    whack swiss; 
    // fairly certain that "whack" is not a keyword,
    // but I am trying to make a point. Trash this instance!

    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}

最佳答案

在不知道用例或您要解决的实际问题的情况下(请阅读 the XY problem,您的问题就是一个很好的例子)最简单的方法就是重新分配:

Cheese swiss("Jarlsberg", 4.99);
...
swiss = Cheese("Gruyère",5.99);

这当然可能需要您实现赋值运算符,但要遵循 rules of three or five无论如何你都应该这样做(但如果你遵循 the rule of zero 则不需要赋值运算符)。

如果您明确想要销毁当前的 swiss 对象,您也可以使用指针:

Cheese* swiss = new Cheese("Jarlsberg", 4.99);
...
delete swiss;
swiss = new Cheese("Gruyère",5.99);

但是指针是一堆你应该避免的蠕虫病毒,在现代 C++ 中并不需要太多。但是如果你想要多态性,就需要指针(或引用)。然后你可以有一个指向实际实例的基类的指针,虚函数之类的东西将按预期工作。

此外,根据您的情况,我们仍然一无所知,您当然可以使用范围界定:

Cheese swiss("Jarlsberg", 4.99);
...
{
    Cheese swiss("Gruyère",5.99);
    // In here the swiss cheese is a Gruyère
    ...
}
// Out here the swiss cheese is a Jarlsberg

虽然像这样隐藏变量名是可行的,但这是一个您应该避免的坏习惯,因为它会给代码的读者带来困惑。另一方面,即使在使用作用域时也没有什么能阻止您使用任何您想要的(有效的)变量名,因此您可以将外部作用域实例命名为 jarlsberg 并将内部作用域实例命名为 gruyere 时,gruyere 对象将在范围的末尾被销毁,就像任何其他嵌套范围变量将被销毁并“消失”一样。

关于c++ - 如何手动删除类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192499/

相关文章:

c++ - std::map 中的 std::pair 作为 const 返回

c++ - 为二维数组动态分配内存时出错

c++ - 返回类型外行定义与声明中的不同

c++ - Qt:QOpenGLWidget 中的文本渲染

php - 可捕获的 fatal error : Object of class "" could not be converted to string in "" on line ""

PHP 多实例单个日志文件

C# : Prevent child modal form from creating instance on taskbar

swift - 值的名称存储在哪里?我怎样才能查看它?

目录中的 C# 类,其 namespace 中没有目录名称

java - 理解 NsdChat 示例应用程序的问题