You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数声明返回int实际返回double?MSVC编译器疑似Bug求证

关于MSVC编译异常的问题求证

我几乎可以确定以下代码是Visual Studio编译器的Bug,但仍需在此求证:

struct A {
    constexpr virtual int f() { return 0; }
};

struct B : A {
    constexpr auto f() { return 1.1; }
};

constexpr int g() {
    B b;
    A & a = b;
    return a.f();
}

static_assert( g() != 1 );
static_assert( g() == 1.1 );

函数g()声明返回int类型,却能通过static_assert(g() == 1.1)编译检查,实际返回double值,该问题在最新MSVC编译器中可复现。请问因B::f()使用auto作为返回类型,该程序是否属于格式错误?


回答

这个程序属于格式错误,具体原因如下:

  • 按照C标准,派生类重写基类虚函数时,返回类型必须与基类虚函数的返回类型兼容。基类A::f()的返回类型是int,而B::f()通过auto推导得到的返回类型是double,这两种类型不满足虚函数重写的返回类型兼容规则(协变返回类型的特殊情况也不适用于此场景)。因此B::f()并未正确重写A::f(),代码本身违反了C标准,属于格式错误。

  • 对于这类格式错误的代码,编译器应当给出诊断信息(编译错误或警告),但MSVC未正确识别该问题,反而允许代码编译并出现异常的编译检查结果,这确实是MSVC的编译器Bug。

内容的提问来源于stack exchange,提问作者Fedor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 10:05:14