变量的作用域与生命周期

Scope vs. Lifetime of Variable(变量的作用域与生命周期)

本文介绍了变量的作用域与生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量的作用域和生命周期有什么关系?如果一个变量超出范围,它的内存是否允许被另一个变量覆盖,或者是否保留空间直到函数离开.

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.

我在 aksing 是因为我想知道下面的代码是否真的有效,或者 *p 是否可能未定义

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;


}

推荐答案

什么是范围?

范围是可以访问变量的区域或代码段.

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

什么是一生?

Lifetime 是对象/变量处于有效状态的持续时间.

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

对于,自动/局部非静态变量Lifetime仅限于它们的Scope.
换句话说,一旦创建它们的范围({,})结束,自动变量就会自动销毁.因此,名称自动开始.

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.

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

所以是的,您的代码有一个未定义行为.

So Yes your code has an Undefined Behavior.

在您的示例中,*p 的范围是创建后的整个函数体.
然而,x 是一个非静态的局部/自动变量,因此 x 的生命周期以它的作用域结束,即 } 的右括号它被创建,一旦范围结束 x 不存在.*p 指向不再存在的东西.

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.

请注意,从技术上讲,x 并不存在于其范围之外,但是可能会发生编译器没有删除 x 的内容,并且人们可能能够访问其内容的情况x 通过指针超出其范围(正如您所做的).但是,执行此操作的代码不是有效的 C++ 代码.这是一个调用未定义行为的代码.这意味着任何事情都可能发生(您甚至可能会看到 x 的价值是完整的)并且人们不应该期望从这样的代码中可以观察到行为.

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.

这篇关于变量的作用域与生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:变量的作用域与生命周期

基础教程推荐