C ++有问题的代码片 [英] C++ problematic code piece
问题描述
我们下周有一个测试练习表,用于学习一点点C ++(在这里仍然是初学者)。我仍然不能找出一个简单的问题。
这就是为什么这些代码片段有问题?
int& p(int z){return z; }
int * h(int z){return& }
解决方案 int * h (int z){return& z}
,传递给函数的参数复制到 z
。该副本只持续的功能。所以一旦函数返回,它不再可用于您的程序。因此,一旦函数返回,你不能有一个有效的指针:正式& z
无效。
版本 int& p(int z){return z}
也是如此。
作为一个练习,看看如果你能知道如果 z
本身是一个引用会发生什么:ie int& p(int& z){return z}
。然后,不会获取副本。但请注意,没有专业人员会写这样的功能。
We got practice sheets for a test next week, for studying a little bit of C++ (still a beginner here). I still can't figure out a simple question.
That is, why are these snippets of code problematic?
int& p(int z) { return z; }
int* h(int z) { return &z; }
解决方案 When int *h(int z) {return &z}
is called, the parameter passed to the function is copied to a variable named z
. That copy only lasts as long as the function. So once the function returns, it is no longer available to your program. So you can't have a valid pointer to it once the function returns: formally &z
is invalidated.
The same is true for the reference version int &p(int z) {return z}
.
As an exercise, see if you can figure out what would happen if z
was itself a reference: i.e. int &p(int& z) {return z}
. Then, a copy would not be taken. But do note that no professional would ever write a function like this.
这篇关于C ++有问题的代码片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!