[英]Why does the C++ compiler makes it possible to declare a function as constexpr, which can not be constexpr?
[英]Returning a C string in a constexpr function: why no warning from the compiler?
考虑以下代码:
constexpr auto f()
{
auto str = "Hello World!";
return str;
}
int main(int argc, char* argv[])
{
static constexpr auto str = f();
std::cout << str << std::endl;
return 0;
}
我的编译器不显示任何警告是否正常? 它是定义的行为吗? 我保证程序会显示"Hello World!"
? 我期待"Hello World!"
不要活在功能范围之外...
在C ++中, 字符串文字具有静态的存储持续时间,并且只要程序运行即可。 因此,从f
返回的字符串文字的指针始终有效。 不涉及分配或解除分配。
请注意,字符串文字的类型为const char[N]
,由于auto
类型推导,在您的情况下,它会转换为const char *
。 如果您打算使用std::string
,则可以直接构造它
auto str = std::string("Hello World!");
或使用operator""s
:
using std::string_literals;
auto str = "Hello World!"s;
但是,由于std::string
不是文字类型,因此该值不能再为constexpr
。
这是汽车的第二个作用 。 您认为的并不总是编译器决定的。 这可能会导致错误的程序员期望-此处的规则是编译器总是获胜 。
这里的事实是, str
是一个字符串(静态存储持续时间)的const char *
。 它可以在构建时完全确定,因此它是有效的constexpr。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.