4

以下 C++ 代码在 Visual Studio 2010 中编译时不会发出警告:


extern void callFunc( int, int );

struct str_wrapper
{
 str_wrapper();
};

extern bool tryParseInt( const str_wrapper& str, int& outValue );

void test()
{
 int x, y;
 if ( tryParseInt( str_wrapper(), x ) && tryParseInt( str_wrapper(), y ) )
 {
  // No warning generated
  callFunc( x, y );
 }
}

但是,如果 str_wrapper 具有用户定义的析构函数,则代码会在 callFunc(x, y) 行上生成警告:

    警告 C4701:使用了可能未初始化的局部变量“y”。


extern void callFunc( int, int );

struct str_wrapper { str_wrapper(); ~str_wrapper(); ///< Causes warning C4701 below };

extern bool tryParseInt( const str_wrapper& str, int& outValue );

void test() { int x, y; if ( tryParseInt( str_wrapper(), x ) && tryParseInt( str_wrapper(), y ) ) { // C4701 generated for following line callFunc( x, y ); } }

如果两个示例都产生了警告,或者两个示例都没有产生警告,我会很高兴。我是否遗漏了一些晦涩的 C++ 规则,或者这是一个编译器错误?

4

1 回答 1

1

不幸的是,我无法使用提供的代码重现该警告。但是,我假设编译器生成它是因为短路评估语言功能。

X 应始终在 tryParseInt 函数中“初始化”,但 Y 的“初始化”仅取决于先前 tryParseInt(str_wrapper(), x) 调用的布尔结果。但是,是的,为什么在 if 块中为 line 生成警告仍然没有任何意义。也许编译器欺骗了自己?

于 2010-07-14T20:15:52.513 回答