Why is there a dummy union member in some implemetations of std::optional?Why is “using namespace std;”...

What would it take to get a message to another star?

Short comic about alien explorers visiting an abandoned world with giant statues that turn out to be alive but move very slowly

Did Pope Urban II issue the papal bull "terra nullius" in 1095?

When did Bilbo and Frodo learn that Gandalf was a Maia?

What if a restaurant suddenly cannot accept credit cards, and the customer has no cash?

When does The Truman Show take place?

Why don't modern jet engines use forced exhaust mixing?

Are there any cons in using rounded corners for bar graphs?

Sums of binomial coefficients weighted by incomplete gamma

Airline power sockets shut down when I plug my computer in. How can I avoid that?

Attacking the Hydra

Does Reckless Attack work with Multiattack when wild shaped?

Why won't the Republicans use a superdelegate system like the DNC in their nomination process?

How can I find an old paper when the usual methods fail?

Is this relation a transitive one?

A+ rating still unsecure by Google Chrome's opinion

Solving pricing problem heuristically in column generation algorithm for VRP

Why do so many people play out of turn on the last lead?

Are they two subordinate clauses?

A Magic Diamond

Does an Irish VISA WARNING count as "refused entry at the border of any country other than the UK?"

Meaning of だけはわからない

Has the speed of light ever been measured in vacuum?

What is a "soap"?



Why is there a dummy union member in some implemetations of std::optional?


Why is “using namespace std;” considered bad practice?Purpose of Unions in C and C++easy way to access union membersC++ equivalent of Rust's Result<T, E> type?memcpy/memmove to a union member, does this set the 'active' member?Static vector internal data layout - `union` vs `std::aligned_storage_t` - huge performance differenceClang LLVM C++ `std::optional<std::optional<int>>` surprising comparison behaviorC++ Union Member Access And Undefined Behaviour






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







21















Both libstdc++ (GNU) and libc++ (LLVM) implement std::optional value storage using a union and both of them include a dummy member.



GNU implementation:



using _Stored_type = remove_const_t<_Tp>;
struct _Empty_byte { };
union {
_Empty_byte _M_empty;
_Stored_type _M_payload;
};


LLVM implementation:



union
{
char __null_state_;
value_type __val_;
};


My question is: Why do we need these _M_empty/__null_state_ members? Is there something wrong with a single-member union?










share|improve this question































    21















    Both libstdc++ (GNU) and libc++ (LLVM) implement std::optional value storage using a union and both of them include a dummy member.



    GNU implementation:



    using _Stored_type = remove_const_t<_Tp>;
    struct _Empty_byte { };
    union {
    _Empty_byte _M_empty;
    _Stored_type _M_payload;
    };


    LLVM implementation:



    union
    {
    char __null_state_;
    value_type __val_;
    };


    My question is: Why do we need these _M_empty/__null_state_ members? Is there something wrong with a single-member union?










    share|improve this question



























      21












      21








      21


      1






      Both libstdc++ (GNU) and libc++ (LLVM) implement std::optional value storage using a union and both of them include a dummy member.



      GNU implementation:



      using _Stored_type = remove_const_t<_Tp>;
      struct _Empty_byte { };
      union {
      _Empty_byte _M_empty;
      _Stored_type _M_payload;
      };


      LLVM implementation:



      union
      {
      char __null_state_;
      value_type __val_;
      };


      My question is: Why do we need these _M_empty/__null_state_ members? Is there something wrong with a single-member union?










      share|improve this question














      Both libstdc++ (GNU) and libc++ (LLVM) implement std::optional value storage using a union and both of them include a dummy member.



      GNU implementation:



      using _Stored_type = remove_const_t<_Tp>;
      struct _Empty_byte { };
      union {
      _Empty_byte _M_empty;
      _Stored_type _M_payload;
      };


      LLVM implementation:



      union
      {
      char __null_state_;
      value_type __val_;
      };


      My question is: Why do we need these _M_empty/__null_state_ members? Is there something wrong with a single-member union?







      c++ c++17 optional unions






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 days ago









      r3mus n0xr3mus n0x

      4,2501 gold badge4 silver badges27 bronze badges




      4,2501 gold badge4 silver badges27 bronze badges



























          1 Answer
          1






          active

          oldest

          votes


















          23














          This is because when using a non-trivial type in a union, suddently the default constructor is deleted.



          This creates all sorts of problem when trying to be constexpr compatible.



          Consider this code:



          struct nontrivial {
          constexpr nontrivial(int o) : u{o} {}
          int u;
          };

          union storage {
          nontrivial nt;
          };

          struct optional {
          storage s;
          };

          constexpr auto run() -> int {
          optional o;
          return o.s.nt.u;
          }

          int main() {
          constexpr int t = run();
          }


          This is ill formed because optional has a deleted constructor.



          Then a simple fix would be to add a constructor that initialize no union member:



          union storage {
          constexpr storage() {} // standard says no
          nontrivial nt;
          };


          But it won't work. Constexpr unions must have at least one active member. It cannot be an empty union. To workaround this limitation, a dummy member is added. This makes std::optional useable in constexpr context.






          share|improve this answer























          • 7





            For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

            – Barry
            2 days ago











          • @TedLyngmo, which version? Tried on 7.4.0 - got an error.

            – r3mus n0x
            2 days ago











          • @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

            – Ted Lyngmo
            2 days ago













          • @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

            – r3mus n0x
            2 days ago











          • @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

            – Ted Lyngmo
            2 days ago














          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57496628%2fwhy-is-there-a-dummy-union-member-in-some-implemetations-of-stdoptional%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          23














          This is because when using a non-trivial type in a union, suddently the default constructor is deleted.



          This creates all sorts of problem when trying to be constexpr compatible.



          Consider this code:



          struct nontrivial {
          constexpr nontrivial(int o) : u{o} {}
          int u;
          };

          union storage {
          nontrivial nt;
          };

          struct optional {
          storage s;
          };

          constexpr auto run() -> int {
          optional o;
          return o.s.nt.u;
          }

          int main() {
          constexpr int t = run();
          }


          This is ill formed because optional has a deleted constructor.



          Then a simple fix would be to add a constructor that initialize no union member:



          union storage {
          constexpr storage() {} // standard says no
          nontrivial nt;
          };


          But it won't work. Constexpr unions must have at least one active member. It cannot be an empty union. To workaround this limitation, a dummy member is added. This makes std::optional useable in constexpr context.






          share|improve this answer























          • 7





            For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

            – Barry
            2 days ago











          • @TedLyngmo, which version? Tried on 7.4.0 - got an error.

            – r3mus n0x
            2 days ago











          • @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

            – Ted Lyngmo
            2 days ago













          • @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

            – r3mus n0x
            2 days ago











          • @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

            – Ted Lyngmo
            2 days ago


















          23














          This is because when using a non-trivial type in a union, suddently the default constructor is deleted.



          This creates all sorts of problem when trying to be constexpr compatible.



          Consider this code:



          struct nontrivial {
          constexpr nontrivial(int o) : u{o} {}
          int u;
          };

          union storage {
          nontrivial nt;
          };

          struct optional {
          storage s;
          };

          constexpr auto run() -> int {
          optional o;
          return o.s.nt.u;
          }

          int main() {
          constexpr int t = run();
          }


          This is ill formed because optional has a deleted constructor.



          Then a simple fix would be to add a constructor that initialize no union member:



          union storage {
          constexpr storage() {} // standard says no
          nontrivial nt;
          };


          But it won't work. Constexpr unions must have at least one active member. It cannot be an empty union. To workaround this limitation, a dummy member is added. This makes std::optional useable in constexpr context.






          share|improve this answer























          • 7





            For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

            – Barry
            2 days ago











          • @TedLyngmo, which version? Tried on 7.4.0 - got an error.

            – r3mus n0x
            2 days ago











          • @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

            – Ted Lyngmo
            2 days ago













          • @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

            – r3mus n0x
            2 days ago











          • @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

            – Ted Lyngmo
            2 days ago
















          23












          23








          23







          This is because when using a non-trivial type in a union, suddently the default constructor is deleted.



          This creates all sorts of problem when trying to be constexpr compatible.



          Consider this code:



          struct nontrivial {
          constexpr nontrivial(int o) : u{o} {}
          int u;
          };

          union storage {
          nontrivial nt;
          };

          struct optional {
          storage s;
          };

          constexpr auto run() -> int {
          optional o;
          return o.s.nt.u;
          }

          int main() {
          constexpr int t = run();
          }


          This is ill formed because optional has a deleted constructor.



          Then a simple fix would be to add a constructor that initialize no union member:



          union storage {
          constexpr storage() {} // standard says no
          nontrivial nt;
          };


          But it won't work. Constexpr unions must have at least one active member. It cannot be an empty union. To workaround this limitation, a dummy member is added. This makes std::optional useable in constexpr context.






          share|improve this answer















          This is because when using a non-trivial type in a union, suddently the default constructor is deleted.



          This creates all sorts of problem when trying to be constexpr compatible.



          Consider this code:



          struct nontrivial {
          constexpr nontrivial(int o) : u{o} {}
          int u;
          };

          union storage {
          nontrivial nt;
          };

          struct optional {
          storage s;
          };

          constexpr auto run() -> int {
          optional o;
          return o.s.nt.u;
          }

          int main() {
          constexpr int t = run();
          }


          This is ill formed because optional has a deleted constructor.



          Then a simple fix would be to add a constructor that initialize no union member:



          union storage {
          constexpr storage() {} // standard says no
          nontrivial nt;
          };


          But it won't work. Constexpr unions must have at least one active member. It cannot be an empty union. To workaround this limitation, a dummy member is added. This makes std::optional useable in constexpr context.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered 2 days ago









          Guillaume RacicotGuillaume Racicot

          19.8k5 gold badges41 silver badges79 bronze badges




          19.8k5 gold badges41 silver badges79 bronze badges











          • 7





            For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

            – Barry
            2 days ago











          • @TedLyngmo, which version? Tried on 7.4.0 - got an error.

            – r3mus n0x
            2 days ago











          • @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

            – Ted Lyngmo
            2 days ago













          • @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

            – r3mus n0x
            2 days ago











          • @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

            – Ted Lyngmo
            2 days ago
















          • 7





            For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

            – Barry
            2 days ago











          • @TedLyngmo, which version? Tried on 7.4.0 - got an error.

            – r3mus n0x
            2 days ago











          • @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

            – Ted Lyngmo
            2 days ago













          • @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

            – r3mus n0x
            2 days ago











          • @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

            – Ted Lyngmo
            2 days ago










          7




          7





          For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

          – Barry
          2 days ago





          For those hunting for the standard quote: eel.is/c++draft/dcl.dcl#dcl.constexpr-4.1

          – Barry
          2 days ago













          @TedLyngmo, which version? Tried on 7.4.0 - got an error.

          – r3mus n0x
          2 days ago





          @TedLyngmo, which version? Tried on 7.4.0 - got an error.

          – r3mus n0x
          2 days ago













          @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

          – Ted Lyngmo
          2 days ago







          @r3musn0x 9.1.1. I don't think 7.4.0 implements LWG 2900.

          – Ted Lyngmo
          2 days ago















          @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

          – r3mus n0x
          2 days ago





          @TedLyngmo, it looks to me that LWG 2900 is only related to the library implementation of optional, so I don't really see the connection... Anyway look here - an error! :)

          – r3mus n0x
          2 days ago













          @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

          – Ted Lyngmo
          2 days ago







          @r3musn0x You are probably correct. Here's a comparison between g++ and clang++ and also a bugreport that seems to be connected to this: bugzilla #886581 It seems to hit my example when templates are involved, but in the bugreport they've managed to trigger the bug without templates.

          – Ted Lyngmo
          2 days ago










          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57496628%2fwhy-is-there-a-dummy-union-member-in-some-implemetations-of-stdoptional%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

          Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

          Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...