Search code examples
c++c++20consteval

Does consteval function can be called with an unused empty class object as an object?


The following code:

struct Foo {
    consteval auto operator+(Foo) const noexcept {
        return Foo{};
    }
};

struct Bar : Foo {};

Foo func() {
    Bar foo, bar;
    return foo + bar;
}

, in which Foo is an empty class, can be compiled with GCC and Clang, but not with MSVC.

MSVC says bar is not a constant expression so it cannot be the argument of the immediate functionoperator+. But GCC and Clang don't think so.

Then which compiler is correct?

Diff view in Compiler Explorer:

https://gcc.godbolt.org/z/o95oK81vn


Solution

  • Looks like a MSVC bug to me. I don't see any reason that the invocation shouldn't be a constant expression.

    In particular bar is not accessed outside its lifetime.