annaa-ka
annaa-ka

Reputation: 7

Union with shared ptr (constructor, destructor)

struct B {
 int b;
}
struct D {
 int * d;
}

class A {
 union {
   B part1;
   D part3;
 } parts;

public:
 A() {
    memset(&parts, 0, sizeof(parts));
 }

Now i want rewrite struct D in this way:

struct D {
 std::shared_ptr<int> d = nullptr;
}

How should I rewrite constructor and destructor of class A to store it in a vector and use functions as emplace_back() which needs default constructor?

Upvotes: 0

Views: 213

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

Use std::variant insted:

struct B { 
  int b;
};

struct D {
  std::shared_ptr<int> d;
};

struct A {
  std::variant<B, D> parts;
};

Upvotes: 1

Related Questions