You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

常量表达式中含std::string的联合体聚合初始化问题

常量表达式中含std::string的联合体聚合初始化问题

我在常量表达式中对包含std::string的联合体进行聚合初始化时遇到了问题,以下示例程序可复现该情况:

constexpr bool f() {
    union U{
        std::string s;
        constexpr ~U(){ s.~basic_string(); }
    } u{};
    return true;
}

static_assert( f() );

我认为u{}应当将std::string s;设为活跃联合体成员并对其进行默认初始化。该代码在MSVC以及搭配libc++的Clang中可正常运行,但在搭配libstdc++的Clang或GCC中会报错:

error: non-constant condition for static assertion
   in 'constexpr' expansion of 'f()'
   in 'constexpr' expansion of '(& u)->f()::U::~U()'
   in 'constexpr' expansion of '((f()::U*)this)->f()::U::s.std::__cxx11::basic_string<char>::~basic_string()'
/opt/compiler-explorer/gcc-13.1.0/include/c++/13.1.0/bits/basic_string.h:803:19:   in 'constexpr' expansion of '((std::__cxx11::basic_string<char>*)this)->std::__cxx11::basic_string<char>::_M_dispose()'
error: accessing 'std::__cxx11::basic_string<char>::<unnamed union>::_M_allocated_capacity' member instead of initialized 'std::__cxx11::basic_string<char>::<unnamed union>::_M_local_buf' member in constant expression

为std::string s;添加默认初始化器std::string s{};可消除GCC中的错误,但Clang仍会报错:

: error: static assertion expression is not an integral constant expression
include/c++/12.2.0/bits/basic_string.h:356:10: note: assignment to member '_M_local_buf' of union with no active member is not allowed in a constant expression
            __c = _CharT();
                ^
include/c++/12.2.0/bits/basic_string.h:519:2: note: in call to '&u.s->_M_use_local_data()'
        _M_use_local_data();
        ^
note: in call to 'basic_string()'
        std::string s{};
                     ^

请问这只是libstdc++的问题,还是该程序本身就属于格式错误?


内容的提问来源于stack exchange,提问作者Fedor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 18:22:41