简体   繁体   中英

constexpr function taking const char*

Im compiling using MSVC v141 with /std:c++17 .

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

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

compiles just fine, whereas

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

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

Fails with:

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'

Is this correct behaviour or a bug in MSVC?

Seems like expected behavior to me. A function declared with constexpr means that it can be evaluated at compile time but not that it is required to be. So your function should also be valid when evaluated at runtime. This is the problem line

constexpr auto bar = foo;

because it attempts to create a constexpr object from a non- constexpr one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM