CodexBloom - Programming Q&A Platform

C++20 std::variant causes unexpected null pointer dereference in polymorphic class

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
C++20 std::variant polymorphism C++

I've been banging my head against this for hours. I'm encountering a frustrating issue with `std::variant` in C++20 while trying to manage a set of polymorphic objects. I've defined a base class `Base` and two derived classes `DerivedA` and `DerivedB`. My intention is to use `std::variant` to hold instances of these derived classes. However, when I attempt to access the member functions of the derived classes, I occasionally get a null pointer dereference error. Here’s the relevant code snippet: ```cpp #include <variant> #include <iostream> #include <memory> class Base { public: virtual void greet() = 0; }; class DerivedA : public Base { public: void greet() override { std::cout << "Hello from DerivedA!" << std::endl; } }; class DerivedB : public Base { public: void greet() override { std::cout << "Hello from DerivedB!" << std::endl; } }; using VariantType = std::variant<std::shared_ptr<DerivedA>, std::shared_ptr<DerivedB>>; void sayHello(VariantType& var) { if (std::holds_alternative<std::shared_ptr<DerivedA>>(var)) { std::get<std::shared_ptr<DerivedA>>(var)->greet(); } else if (std::holds_alternative<std::shared_ptr<DerivedB>>(var)) { std::get<std::shared_ptr<DerivedB>>(var)->greet(); } } int main() { VariantType varA = std::make_shared<DerivedA>(); sayHello(varA); VariantType varB = std::make_shared<DerivedB>(); sayHello(varB); // Simulate a null pointer dereference varB = nullptr; sayHello(varB); return 0; } ``` In this code, I create a `VariantType` variable that can hold either `std::shared_ptr<DerivedA>` or `std::shared_ptr<DerivedB>`. When I pass `varB` after assigning it to `nullptr`, I expect the program not to crash, but instead, I receive a segmentation fault when trying to dereference it. I have already implemented checks using `std::holds_alternative`, but it seems that the dereference happens before those checks, leading to a null pointer access. I’ve also tried using `std::get_if` instead of `std::get`, but the behavior remains the same. Am I missing something in my checks, or is there a better pattern to follow when using `std::variant` with polymorphic types? Any insights would be greatly appreciated! My development environment is Windows.