簡體   English   中英

與共享 ptr 聯合(構造函數、析構函數)

[英]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));
 }

現在我想以這種方式重寫 struct D:

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

我應該如何重寫 class A 的構造函數和析構函數以將其存儲在向量中並使用需要默認構造函數的emplace_back()函數?

使用std::variant insted:

struct B { 
  int b;
};

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM