0
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?

timrau
  • 22,578
  • 4
  • 51
  • 64
annaa-ka
  • 7
  • 2
  • 3
    If you write `std::variant` instead, you have to rewrite exactly nothing. – Quimby Aug 16 '22 at 05:23
  • 1
    Does this answer your question? [Why compiler doesn't allow std::string inside union?](https://stackoverflow.com/questions/3521914/why-compiler-doesnt-allow-stdstring-inside-union) – Quimby Aug 16 '22 at 05:28

1 Answers1

1

Use std::variant insted:

struct B { 
  int b;
};

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

struct A {
  std::variant<B, D> parts;
};
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93