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?
}
}
}
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With