When I compile the following code with -std=c++26
#include <string>
class Foo {
public:
constexpr static auto foo = std::string{"this_is_ok"};
constexpr static auto bar = std::string{"a_very_long_string_that_probably_dont_fit_in_SSO"};
};
On Compiler Explorer
I got
<source>:6:27: error: constexpr variable 'bar' must be initialized by a constant expression
6 | constexpr static auto bar = std::string{"a_very_long_string_that_probably_dont_fit_in_SSO"};
| ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:6:27: note: pointer to subobject of heap-allocated object is not a constant expression
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/15.0.0/../../../../include/c++/15.0.0/bits/allocator.h:193:31: note: heap allocation performed here
193 | return static_cast<_Tp*>(::operator new(__n));
|
Does this behavior of std::string conform to the standard?
I need a workaround to have some long std::string objects in constexpr.
New contributor
nofe1248 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1