簡體   English   中英

您可以為具有 const 成員的聯合編寫一個復制構造函數嗎?

[英]Can you write a copy constructor for a union with const members?

假設我有一個包含const成員聯合的結構,如下所示:

struct S
{
  // Members

  const enum { NUM, STR } type;

  union
  {
    const int a;
    const std::string s;
  };

  // Constructors

  S(int t_a) : type(NUM), a(t_a);

  S(const std::string & t_s) : type(STR), s(t_s);

};

到現在為止還挺好。 但是現在說我想為這種類型編寫一個復制構造函數。

這似乎並不涉及做任何邪惡的事情,但是由於我需要在成員初始值設定項中初始化 const 成員,因此我不知道如何根據取決於type成員的邏輯來執行此操作。

問題:

  • 是否可以編寫此構造函數?

  • 如果不是,這本質上是一種語法上的疏忽,還是存在某種語言不能支持這樣的事情的根本原因?

是的,可以在這里編寫復制構造函數。 實際上它已經在std::variant實現中完成,它應該支持const類型等。 所以你的類S可以替換為

using S = std::variant<const int, const std::string>;

但是,如果由於圓頂原因您不能使用std::variant則可以使用std::construct_at函數編寫復制std::construct_at函數,如下所示:

#include <string>

struct S {
  const enum { NUM, STR } type;

  union {
    const int a;
    const std::string s;
  };

  S(int t_a) : type(NUM), a(t_a) {}
  S(const std::string & t_s) : type(STR), s(t_s) {}
  S(const S & rhs) : type(rhs.type) {
      if ( type == NUM ) std::construct_at( &a, rhs.a );
      if ( type == STR ) std::construct_at( &s, rhs.s );
  }
  ~S() {
      if ( type == STR ) s.~basic_string();
  }
};

int main() {
    S s(1);
    S u = s;

    S v("abc");
    S w = v;
}

演示: https : //gcc.godbolt.org/z/TPe8onhWs

暫無
暫無

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

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