采用 const char* 的 constexpr 函数

constexpr function taking const char*

我正在使用 MSVC v141 和 /std:c++17 进行编译。

constexpr const char* test(const char* foo) {
    return foo + 1;
}

constexpr const char* bc = test("abc");

编译得很好,而

constexpr const char* test(const char* foo) {
    constexpr auto bar = foo;
    return bar + 1;
}

constexpr const char* bc = test("abc");

失败:

error C2131: expression did not evaluate to a constant

failure was caused by a read of a variable outside its lifetime

note: see usage of 'foo'

这是正确的行为还是 MSVC 中的错误?

对我来说似乎是预期的行为。用 constexpr 声明的函数意味着它可以在编译时求值,但不是必须的。因此,您的函数在运行时评估时也应该有效。这是问题行

constexpr auto bar = foo;

因为它试图从非 constexpr 对象创建 constexpr 对象。