CodexBloom - Programming Q&A Platform

std::variant causing 'bad_variant_access' in C++20 with custom types

👀 Views: 947 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
c++20 std-variant error-handling C++

I'm a bit lost with I tried several approaches but none seem to work. I'm facing an issue when using `std::variant` in my C++20 application. I've defined a `std::variant` that can hold either a `std::string` or a custom struct, but I'm encountering a `std::bad_variant_access` exception when trying to retrieve the value. Here's my setup: ```cpp #include <variant> #include <string> #include <iostream> #include <stdexcept> struct CustomType { int id; std::string name; }; int main() { std::variant<std::string, CustomType> myVariant; myVariant = CustomType{1, "Test"}; try { // Attempting to access the CustomType CustomType value = std::get<CustomType>(myVariant); std::cout << "ID: " << value.id << ", Name: " << value.name << std::endl; } catch (const std::bad_variant_access& e) { std::cerr << "Error: " << e.what() << std::endl; } // Now let's change it to std::string myVariant = std::string("Hello"); // Try to access CustomType again try { CustomType value = std::get<CustomType>(myVariant); } catch (const std::bad_variant_access& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } ``` In the second `try` block, I'm trying to access the `CustomType` after assigning a `std::string` to `myVariant`. This results in the `std::bad_variant_access` exception, which is expected. However, I thought that if I catch the exception, I could simply handle the situation and continue. The issue arises when I try to access the `CustomType` again after assigning a `std::string`. I would expect it to not throw an exception during the first `std::get<CustomType>(myVariant)` call since I am indeed accessing the variant after a valid assignment. I've confirmed that the variant is indeed holding a `CustomType` before the first access, and I suspect this behavior might be related to the lifecycle of the variant and its state management. Has anyone experienced similar issues or can provide insight on the correct usage of `std::variant` with custom types in C++20? Any help would be appreciated! My development environment is Ubuntu. What's the best practice here? Any ideas what could be causing this? What am I doing wrong? I've been using C++ for about a year now. I'd really appreciate any guidance on this.