VS2017 版本 15.8.3 成功编译内联方法,而不返回所需值

VS2017 version 15.8.3 successfully compiles inline method without returning a required value

本文关键字:返回 方法 版本 成功 编译 VS2017      更新时间:2023-10-16

我用VS2017版本15.8.3编译了以下代码。其警告级别设置为/W4。该代码包含两个简单的 getter,其中一个GetM()内联的。

GetM()内联 getter 没有return语句。但是,VS2017愉快地编译了代码,没有任何警告或错误。

如果GetN()方法的return n;语句被注释掉,则会导致error C4716: 'Simple::GetN': must return a value

class Simple
{
int m = 0;
int n = 0;
public:
int GetM() const { /* No return here. */ }
int GetN() const;
};
int Simple::GetN() const
{
return n;
// No return here results in compiler error below. 
// error C4716: 'Simple::GetN': must return a value
}
int main()
{
Simple obj;
}

问题:编译器是否也应该为内联方法GetM()生成error C4716

类定义中完全定义的方法是一种内联的。如果未直接在使用它的位置内联扩展,则会在类主体外部编译。这是一个神奇的调味料,它允许方法查看类中在其之后定义的任何成员。

如果不使用它,编译器可能没有足够深入地查看它以发现错误。也许它根本不看它。也许它会生成警告,也许不会。这取决于编译器。Visual Studio似乎已选择将缺少的返回语句报告为错误,但不检查未使用的inline(或内联(函数。

通过将main更改为

int main()
{
Simple obj;
obj.GetM();
}

我可以让Visual Studio为gGetM生成错误C4716,因为现在必须编译该函数,无论是否内联。

我也可以

inline int Simple::GetN() const 
{ 
}

明确GetNinline并"消除"错误。

这都是高度编译器,甚至可能是编译器选项,特定于。