Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a destructor from being called on a stack allocated object?

Tags:

c++

destructor

I have a union-like class with a member that may or may not be garbage depending on a boolean flag also set in that same class.

Obviously, I do not want that garbage to be destructed when my class goes out of scope. How to prevent a class member from being destructed?

I know this could be achieved with pointers and dynamically allocated memory, but I am looking for a more simple solution.

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?
        }
    }
}
like image 896
Jeroen Avatar asked Oct 19 '25 17:10

Jeroen


1 Answers

You can use std::optional (since C++17), which won't cause dynamic memory allocation. e.g.

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 */ }
};

BTW: The member has_child could be replaced by std::optional::has_value().

like image 160
songyuanyao Avatar answered Oct 22 '25 05:10

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!