English 中文(简体)
为什么这个编译(用于函数初始化之前)?
原标题:
  • 时间:2009-04-08 21:21:11
  •  标签:

考虑这段代码(使用装运箱,因为它年代熟悉和容易看到不建造,但没有什么特别的类),测试在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

最佳回答

你看到的行为sTest1 c++标准没有定义。奇怪的和不对的但它编译一些编译器。

看到litb年代回答以下线程更多细节:< a href = " https://stackoverflow.com/questions/723344/method-running-on-an-object-before-the-object-has-been-initialised/723358 # 723358 " >方法运行在对象被初始化一个对象之前? < / >

问题回答

有几个问题相关的现象在过去的几天里。

My understanding is that even though sTest1 is not initialized, it is already a valid identifier (e.g., in C you could call sizeof on it), it just doesn t have contents. So when you make the call to DoSomething, you are passing a reference to an uninitialized variable which is legitimate but dangerous.

我猜,在运行时返回的问题,因为你正试图做一个return-by-value(拷贝构造函数)本质上是未初始化的内存空间,应该是一个字符串。取决于cstring存储,代码可能是寻找一个空终结者或代表分配的字节数。





相关问题
热门标签