范围与变量的寿命 [英] Scope vs. Lifetime of Variable

查看:210
本文介绍了范围与变量的寿命的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量的作用域和生命周期之间的关系是什么?
如果一个变量超出范围,是允许被另一个变量覆盖的内存,或者是保留到该函数剩余的空间。



我是aksing,因为我想知道下面的代码是否真正起作用,还是可能是* p可能未定义

  foo(){
int * p;
{
int x = 5;
p =& x;
}
int y = * p;


}


解决方案

< blockquote>

什么是范围?


是可以访问变量的代码的区域或部分。


生命周期 是指生命周期的持续时间,其中生命周期 对象/变量处于有效状态。



对于 自动/本地非静态变量生命周期仅限于它们的 Scope

换句话说,自动变量会在范围 {,} )。


您的代码示例中有什么问题? b $ b

因此,您的代码有未定义行为



您的示例范围 * p 是创建后的整个函数体。

不过, x 是一个非静态局部/自动变量,因此 x 的生命周期以它的范围结束,即} 其中它被创建,一旦作用域结束 x 不存在。 * p 指向不再存在的内容。



请注意,技术上 x 不存在超出其范围,但是可能发生编译器没有删除内容 x ,并且可以通过指针访问 x 的内容do )。但是,这样做的代码不是有效的C ++代码。它是一个调用未定义行为的代码。这意味着任何事情都可能发生(你可能会看到 x 的价值是完整的),并且不应该期望这样的代码的可观察的行为。


What is the relation between the scope and the lifetime of a variable? If a variable is out of scope, is the memory of it allowed to be overwritten by another variable, or is the space reserved until the function is left.

I am aksing because I want to know whether the code below actually works, or whether it can be that *p might be undefined

foo() {
  int *p;
  {
    int x = 5; 
    p = &x;
  }
  int y = *p;


}

解决方案

What is Scope?

Scope is the region or section of code where a variable can be accessed.

What is a lifetime?

Lifetime is the time duration where an object/variable is in a valid state.

For, Automatic/Local non-static variables Lifetime is limited to their Scope.
In other words, automatic variables are automagically destroyed once the scope({,}) in which they are created ends. Hence the name automatic to begin with.

What is wrong in your code example?

So Yes your code has an Undefined Behavior.

In your example scope of *p is entire function body after it was created.
However, x is a non-static local/automatic variable and hence the lifetime of x ends with it's scope i.e the closing brace of } in which it was created, once the scope ends x does not exist. *p points to something that doesn't exist anymore.

Note that technically x does not exist beyond its scope however it might happen that the compiler did not remove the contents of x and one might be able to access contents of x beyond its scope through a pointer(as you do).However, a code which does this is not a valid C++ code. It is a code which invokes Undefined Behaviour. Which means anything can happen(you might even see value of x being intact) and one should not expect observable behaviors from such a code.

这篇关于范围与变量的寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆