CodexBloom - Programming Q&A Platform

std::variant not holding value after being assigned in a class with copy assignment operator in C++20

👀 Views: 192 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
c++20 std::variant copy-assignment cpp

I recently switched to I need help solving I've looked through the documentation and I'm still confused about I'm working with an scenario with `std::variant` in a class that implements a copy assignment operator... I have a class `DataHolder` that contains a `std::variant<int, std::string>`, and after I assign a new object to it, the variant seems to lose its value. Here's the relevant part of the code: ```cpp #include <iostream> #include <variant> #include <string> class DataHolder { public: std::variant<int, std::string> data; DataHolder(int value) : data(value) {} // Custom copy assignment operator DataHolder& operator=(const DataHolder& other) { if (this != &other) { data = other.data; // Assignment happens here } return *this; } }; int main() { DataHolder holder1(42); DataHolder holder2(0); holder2 = holder1; // Check value std::cout << std::get<int>(holder2.data) << std::endl; return 0; } ``` When I run this code, I expect `holder2` to hold the integer value `42` after the assignment. However, I sometimes get a runtime behavior, specifically a `bad_variant_access`, when the variant is expected to hold an `int`. I suspect it might have to do with how the variant is being copied or assigned. I've tried using both the default copy assignment operator and my custom version, but the question continues. Additionally, I've confirmed that the state of `holder1` is valid at the time of the assignment. Is there something I'm missing regarding the copy semantics of `std::variant`, especially in C++20? Could this be related to how `std::variant` is implemented or how my custom operator is defined? Any insights would be appreciated. How would you solve this? Hoping someone can shed some light on this. What's the best practice here? For reference, this is a production CLI tool. Thanks for any help you can provide!