考虑这段代码(使用装运箱,因为它年代熟悉和容易看到不建造,但没有什么特别的类),测试在Visual Studio 2008中:
CString DoSomething( const CString& sString )
{
return sString;
}
CString sTest1 = DoSomething( sTest1 ); // Compiles (no warnings), fails at runtime
CString sTest2( DoSomething( sTest2 ) ); // Doesn t compile
CString sTest3; sTest3 = DoSomething( sTest3 ); // Compiles, self-assignment, works
我理解c++标准,可以编译成Test1 Test2自动编译时优化,提供适当的构造函数是可用的(默认情况下,将生成相同的第一个测试)。然而,值得注意的是,这种行为并不等同于Test3,将正常工作。
现在我明白为什么Test1不工作,为什么Test2没有编译。我好奇的是为什么Test1编译呢?这是允许的标准,开放的解释,一个缺陷在VS2008中编译器,一个缺乏init-before-use静态检查,还是别的什么?有没有办法强制编译器至少给予警告在这种情况下(Test1编译清洁与马克斯警告级别在VS2008中)?是什么理由c++规范允许这个构造?
编辑:或者,有什么方法可以强制编译器来编译Test1和Test2(因此触发错误)?
Edit to add verbatim error message for Test2: error C2065: sTest2 : undeclared identifier