在C++标准中,constexpr不能直接用于std::string,因为std::string是一个复杂的类,其构造、赋值和销毁操作都涉及动态内存分配和释放,这些操作无法在编译时完成。constexpr要求其变量或函数返回值在编译时就完全确定,而std::string无法满足这一要求。 3. 给出在C++中如何使用constexpr声明字符串字面量的示例 虽然不能...
#include <string> int main() { constexpr std::string s("abc"); } 和: g++-9 -std=c++2a main.cpp 有错误: error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal std::vector 讨论于: 无法创建 const...
无法使用std::vector和std::string等常用容器。 C++20 往前迈进了一大步,constexpr函数可以进行有限制的动态内存分配和std::vector/std::string的使用。比如: 使用new和delete进行动态内存分配和回收: constexpr int sum(int n) { auto p = new int[n]; std::iota(p, p + n, 1); auto t = std::a...
你发现没,GCC 的 std::string 的缺陷可不止 constexpr,在 FFI 方面也是劣势。所以很多人被迫重复造...
但是,我无法链接到模块中的"constexpr std::string_view“。相比之下,我可以在模块内使用string_view (而不是constexpr),也可以在模块之外使用"constexpr std::string_view“。此外,在模块中使用constexpr的其他用途,例如整数,也不会出现此问题。 下面是重新创建错误的最小代码: 模块接口单元(my_string.cpp): ...
constexpr std::string_view foo("abc"); // C2131: expression did not evaluate to a constant constexpr std::string_view foo("abc", 3); // No error Looking deeper into the code, the root of the problem seems to be that the std::char_traits::length() function is...
constexpr std::string extendedPrefix{"\\\?\\"}; int main() { std::cout << "extendedPrefix: " << extendedPrefix << "\n"; return 0; } this code compile with Command Line Prompt. check below picture. But in Visual S...
conststd::string A::name("aaa"); 一个特例是,如果static常量的类型是内置的整数类型,如char、int、size_t等,那么可以在类中直接给出初始值,且不需要在类外再进行定义了。编译器会将这种static常量直接替换为相应的初始值,相当于宏替换。但如果在代码中我们像正常变量那样使用这个static常量,如取它的地址,而...
std::string在有适当支持的情况下应该是constexpr的,以便在编译时评估字符串操作,但它似乎并非如此。 我误解了标准库中__cpp_lib_constexpr_string宏的效用。 C++20 将在constexpr上下文中提供更多文本操作的灵活性。 我已经做了功课,发现了 Stack Overflow 上关于类似问题或如何在constexpr上下文中使用std::string...
conststd::stringhello="Hello World!";//Right!constexprstd::stringhello="Hello World!";//Wrong! 这是因为编译期间无法构造std::string对象,只能在运行时被定义出来,因此是不可变量。很多时候我们会被迷惑,遵照“常量建议定义在头文件中”的原则,便将所有const修饰的全局量定义在头文件。事实上像上面的std:...