【发布时间】:2022-01-03 21:30:02
【问题描述】:
显然,GCC 的 libstdc++ 还没有添加 constexpr std::string(从 GCC v11.2 开始)。
这段代码:
#include <iostream>
#include <string>
int main( )
{
constexpr std::string str { "Where is the constexpr std::string support?"};
std::cout << str << '\n';
}
无法编译:
time_measure.cpp:37:31: error: the type 'const string' {aka 'const std::__cxx11::basic_string<char>'} of 'constexpr' variable 'str' is not literal
37 | constexpr std::string str { "Where is the constexpr std::string support?"};
| ^~~
In file included from c:\mingw64\include\c++\11.2.0\string:55,
from c:\mingw64\include\c++\11.2.0\bits\locale_classes.h:40,
from c:\mingw64\include\c++\11.2.0\bits\ios_base.h:41,
from c:\mingw64\include\c++\11.2.0\ios:42,
from c:\mingw64\include\c++\11.2.0\ostream:38,
from c:\mingw64\include\c++\11.2.0\iostream:39,
from time_measure.cpp:2:
c:\mingw64\include\c++\11.2.0\bits\basic_string.h:85:11: note: 'std::__cxx11::basic_string<char>' is not literal because:
85 | class basic_string
| ^~~~~~~~~~~~
c:\mingw64\include\c++\11.2.0\bits\basic_string.h:85:11: note: 'std::__cxx11::basic_string<char>' does not have 'constexpr' destructor
我的问题是,当字符串包含超过 16 个chars(因为 GCC 的 SSO 缓冲区大小为 16)时,这些字符串将如何在后台工作?有人可以给我一个简短的解释吗? 一个简单的构造函数会在堆栈上创建字符串对象并且从不使用动态分配吗?
这段代码:
std::cout << "is_trivially_constructible: "
<< std::boolalpha << std::is_trivially_constructible<const std::string>::value << '\n';
打印这个:
is_trivially_constructible: false
现在在这里使用constexpr(显然不能使用 GCC v11.2 编译):
std::cout << "is_trivially_constructible: "
<< std::boolalpha << std::is_trivially_constructible<constexpr std::string>::value << '\n';
结果会是true,如下所示吗?
is_trivially_constructible: true
我的目标
我的目标是做类似的事情:
constexpr std::size_t a { 4 };
constexpr std::size_t b { 5 };
constexpr std::string msg { std::format( "{0} + {1} == {2}", a, b, a + b ) };
std::cout << msg << '\n';
std::format 和 constexpr std::string 都不能在 GCC v11.2 上编译。
【问题讨论】:
-
一个简单的构造函数会在堆栈上创建字符串对象并且从不使用动态分配吗? 没有必要,因为在常量表达式中允许动态分配,只要在持续评估结束之前,它全部被释放。
-
c++20 增加了将 constexpr 与分配器一起使用的能力 cppstories.com/2021/constexpr-new-cpp20
-
该变量声明无效。
std::string将在持续评估中可用。但它并不是神奇的文字类型。 -
@Artyer - 明确?你不能对它的实现做任何假设。
-
@Artyer - 您忽略了对其数据成员的约束。标准没有强加为文字类型。再说一遍,除非它是明确的字面意思,否则你不能这样宣称它。
标签: c++ c++20 constexpr stdstring