advanced patterns with std::variant when using std::visit and dynamically allocated memory in C++20
This might be a silly question, but Hey everyone, I'm running into an issue that's driving me crazy. I'm working with an scenario when using `std::variant` along with `std::visit` in my C++20 project. I have a `std::variant` that can hold either a `std::string` or a pointer to an object. When I attempt to access the value using `std::visit`, it seems to be causing unexpected behavior, particularly when the pointer is dynamically allocated. Here's a simplified version of what I'm trying to achieve: ```cpp #include <variant> #include <iostream> #include <string> struct MyData { int value; MyData(int v) : value(v) {} }; int main() { std::variant<std::string, MyData*> data; data = new MyData(42); // dynamically allocating MyData object std::visit([](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, std::string>) { std::cout << "String: " << arg << '\n'; } else if constexpr (std::is_same_v<T, MyData*>) { std::cout << "MyData value: " << arg->value << '\n'; } }, data); // Clean up the allocated memory delete std::get<MyData*>(data); return 0; } ``` The question arises when I run this code: I see the expected output initially, but then I encounter a segmentation fault when trying to `delete` the dynamically allocated `MyData` object. It seems that the variant does not hold the pointer correctly after the visit. I've also tried using `std::unique_ptr` instead, but that leads to a different set of issues regarding ownership and double deletion. I considered using `std::shared_ptr`, but it feels like overkill for this situation. My goal is to efficiently manage this memory without running into access violations. What am I doing wrong here? How can I properly manage the lifecycle of the data stored in `std::variant`? Are there better design patterns or best practices for handling such cases in C++20? I'm working on a CLI tool that needs to handle this.