Search code examples
c++memory-leaksc++17void-pointersstd-variant

What will destructor of a std::variant do if it contains void* data


I have just started using std::variant in my projects. I have a doubt. What will the destructor of std::variant do in the code shown below. Variant holds a void* data. Once variant goes out of scope, I think it will only free the memory of void* but not the actual object the pointer was pointing to. So there will be memory leak in this case. I would like to know if my understanding is correct or not.

#include <iostream>
#include <memory>
#include <variant>
using namespace std;

class A {
    public:
    ~A(){
        cout<<"Destructor called"<<endl;
    }
};


int main() {
    std::variant<void*> data;
    A* b = new A();
    data = (void*)b;
    return 0;
}

Solution

  • When the variant destructor fires, it will call the destructor for whatever type of item is stored in the variant at that point. If that’s a void*, then C++ will say “okay, I will clean up the void*, and since that’s a primitive type, that’s a no-op.” It won’t look at the void*, realize that it’s actually a pointer to an A, and then delete the pointer as though it’s an A*.

    The comments have pointed out that it’s fairly unusual to use a variant of a void*. A void* means “I’m pointing at something, and it’s up to you as the user to keep track of what it is and do the appropriate casting and resource management.” A variant means “I’m holding one of the following actual things, and I want C++ to remember which one and to do the appropriate resource management for me.” You may want to rethink your design, as there might be an easier way to do whatever you’re aiming to do here.