CodexBloom - Programming Q&A Platform

std::variant not holding correct type after assignment in C++20 with lambdas

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
c++20 std-variant lambda std-get bad-variant-access C++

I've been struggling with this for a few days now and could really use some help. I'm working with an scenario with `std::variant` in C++20 where it seems to lose its type after being assigned via a lambda function. Here’s a minimal example of what I've been trying: ```cpp #include <iostream> #include <variant> #include <string> int main() { std::variant<int, std::string> myVariant; auto assignVariant = [&]() { myVariant = std::string("Hello"); }; assignVariant(); // Check the current type if (std::holds_alternative<std::string>(myVariant)) { std::cout << "Variant holds a string: " << std::get<std::string>(myVariant) << '\n'; } else { std::cout << "Variant does not hold a string.\n"; } } ``` When I run this, the output indicates that the variant does hold a string, which is expected. However, if I assign another value right after: ```cpp myVariant = 42; // Assigning an int ``` Checking the type again shows that the variant successfully holds the int. But when I try to access it using `std::get<std::string>(myVariant)`, I receive a `std::bad_variant_access` behavior. This behavior suggests that the variant does not hold a `std::string`, even though it seemed to. I've verified that my lambda function executes correctly, but I'm not sure if there's an scenario with the lifetime of the lambda or how the assignment is handled. I've tried using `std::visit` to check the contents of my variant after each assignment, and it seems to behave correctly. However, immediately accessing the string type leads to the crash. Is there a known scenario with `std::variant` in C++20 regarding lambdas, or am I missing something in my implementation? Any insights or suggestions on how to properly manage this would be appreciated. This is part of a larger application I'm building.