如何阻止在堆栈分配对象上调用析构函数?

Jer*_*oen 3 c++ destructor

我有一个类似联合的类,其成员可能是垃圾,也可能不垃圾,具体取决于同一类中也设置的布尔标志.

显然,当我的课程超出范围时,我不希望破坏垃圾.如何防止类成员被破坏?

我知道这可以用指针和动态分配的内存来实现,但我正在寻找一个更简单的解决方案.

class MyContainer {
    bool has_child;
    MyChild child;

public:
    MyContainer(MyChild child) { this->has_child = true; this->child = child; }
    MyContainer() { this->has_child = false; }

    ~MyContainer() {
        if (!this->has_child) {
            // What to do here?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

您可以使用std :: optional(自C++ 17开始),这不会导致动态内存分配.例如

class MyContainer {
    bool has_child;
    std::optional<MyChild> child;

public:
    MyContainer(MyChild child) : child(child) { this->has_child = true; }
    MyContainer() { this->has_child = false; }

    ~MyContainer() { /* nothing special need to do */ }
};
Run Code Online (Sandbox Code Playgroud)

顺便说一句:该成员has_child可以被替换std::optional::has_value().

  • @JeroenBollen:如果你可以自由选择你的编译器,那么你可以很容易地成为C++ 17功能的早期采用者,如果你真的想要的话.例如,Visual C++ 2017支持`std :: optional`和许多其他带有`/ std:c ++ latest`标志的C++ 17特性. (2认同)