I'm wondering why std::string can't be constexpr if it's a stack variable:
#include <string>
#include <iostream>
#include <cstring>
constexpr std::string str15 {"123456789012345"}; // This compiles!
struct Foo
{
constexpr Foo() : a(6) {
for (int i = 0; i < 8; ++i)
buff[i] = 0;
}
int a;
char buff[8];
};
constexpr void func()
{
constexpr Foo f{}; // This compiles
constexpr std::string str15 {"123456789012345"}; // This doesn't compile
}
int main() {
func();
return 0;
}
Error:
'std::string{std::__cxx11::basic_string<char>::_Alloc_hider{((char*)(& str15.std::__cxx11::basic_string<char>::<anonymous>.std::__cxx11::basic_string<char>::<unnamed union>::_M_local_buf))}, 15, std::__cxx11::basic_string<char>::<unnamed union>{char [16]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', 0}}}' is not a constant expression
I get the stack variable and the static variable are different places in memory, but the compiler will accept arbitrary objects as local variables as constexpr. My Foo class doesn't have a const char* as argument, so that's a difference, but it's not as if const char* constructor can't be used in constexpr, because higher above:
constexpr std::string str15 {"123456789012345"}; // This compiles
constexprcan be notstaticin the first place! A compile time constant must have static storage(maybe in the code segment). Why can it even treated like automatic objects?