2

Let's say my C++ class has a private union.

class Thingy
{
public:
    explicit Thingy( const std::string & v ); // initializes u.value_
    explicit Thingy( const std::share_ptr & p ); // initializes u.ptr_

    ~Thingy();

    // ... other functions ...

private:

    union Value
    {
        std::string value_;
        std::shared_ptr ptr_;
    };

    enum Tag
    {
        String,
        Pointer
    };

    Tag tag_;
    Value u_;
};

When the program calls the implicit destructor for Thingy::Value::~Value(), which member variable's destructor gets called? The one for value_ or the one for ptr_?

How would I guarantee the right one gets called?

Thanks!

RichS
  • 540
  • 1
  • 6
  • 12

0 Answers0