2008年1月24日星期四

下面的函数可能有什么样的运行时错误?

string &func(){
string str;
while(cin>>str){
}
return str;
}

直接在VC6.0中编译,给出的错误是
warning C4172: returning address of local variable or temporary

Compiler Warning (level 1) C4172:returning address of local variable or temporary

A function returned the address of a local variable or a temporary. Local variables and temporaries are destroyed when a function returns; consequently the address returned will almost certainly be invalid.

返回局部变量的地址或者临时变量。因为二者在函数返回时就会销毁,所以返回的地址几乎肯定是无效的。

When returning the address of a variable, you should return the address of a global variable or a dynamically allocated variable, which will continue to exist after the function ends.

应该返回全局变量或者动态分配的变量,这样的变量会在函数结束后依然存在。

这里的while(cin>>str){}并不要求输入任何东西即返回。
而if(cin>>str){printf("I will not be printed");}else{printf("I will be printed!")}

没有评论: