[Bug c++/102286] [constexpr] construct_at incorrectly starts union array lifetime in some cases

gcc at ebasoft dot com.pl gcc-bugzilla@gcc.gnu.org
Fri Feb 18 13:43:57 GMT 2022


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102286

Artur Bać <gcc at ebasoft dot com.pl> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |gcc at ebasoft dot com.pl

--- Comment #4 from Artur Bać <gcc at ebasoft dot com.pl> ---
This is not legal in c++20 but gcc allows accessing not active member of a
union in constexpr

https://godbolt.org/z/KsEhffeEa

clang refuses and it is right

"construction of subobject of member 'object' of union with active member
'init' is not allowed in a constant expression"
With c++20 there is no way to have aligned_storage for not trivial type in
constexpr (storage without initialization, not std::array that requires
construction of non trivial objects upon member activation)

https://godbolt.org/z/9EGrf8fbr

#include <memory>

    struct foo
        {
        int * i;
        constexpr foo() { i = new int; }
        constexpr ~foo() { delete(i); }
        };
    union storage
    {
      constexpr storage() 
          : init{}
      {}
      constexpr ~storage() {}

      foo object[1];
      char init = '\0';
      };

consteval bool test()
    {
    storage u;
    auto p = std::addressof(u.object[0]);
    std::construct_at<foo>(p);
    std::destroy_at(p);
    return true;
    }

int main()
{ 
    static_assert( test() );
    return test();
}


More information about the Gcc-bugs mailing list