为什么不能在声明范围之外访问用 new 声明的变量?
Why can't access a variable declared with new outside of the scope it was declared in?
我知道这是一个愚蠢的问题,我不明白我是怎么卡住的,但我在这里。
在此代码中,当我尝试在声明的范围之外访问 x 时(在堆上声明),它告诉我 x 未在此范围内声明.
{
int * x = new int;
}
*x = 5; /// Error
我以前从来没有遇到过这个问题。在我调用 delete x;
之前 x 不应该存在吗?
变量x
只能在声明的范围内访问。
无论x
的状态如何,分配的缓冲区一直保留到删除,因此当x
在缓冲区被删除之前和指针存储到[=10=之前变得不可用时,就会发生内存泄漏] 被复制到范围外可用的任何地方。
声明某物与初始化某物不同,事实上:
{
int * x = new int;
}
*x = 5; /// Error
永远不会工作(至少在 C++ 中),但是这个:
int* x;
{
x = new int;
}
*x = 5;
会起作用,因为 x
的声明和使用在同一范围内
x
(一个指针)和它指向的东西(一个 int)是有区别的。
int 不是“在堆上声明的”- 堆不是作用域,也不包含声明。另一方面,x
只是堆栈上的一个普通变量,当其包含块的执行完成时就会消失。
堆上的int
确实继续存在于堆上,但是当你扔掉x
(指针)你就没有办法访问它了,int
已经泄露了。
Why can't access a variable declared with new outside of the scope it was declared in?
因为语言规则说变量名的范围已经结束:
[basic.scope.declarative]
Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.
In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
A name declared in a block ([stmt.block]) is local to that block; it has block scope.
Its potential scope begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of its block.
此外,随着名称的范围,对象的生命周期也结束了,因此由变量命名的对象不再存在于块范围之外。
Shouldn't x exist until I call delete x;?
没有。您混淆了具有自动存储的变量 x
和 x
指向的动态对象。动态对象仍然存在,但无法访问,因为您丢失了指针。这种仅指向动态内存的指针的丢失称为内存泄漏。
我知道这是一个愚蠢的问题,我不明白我是怎么卡住的,但我在这里。 在此代码中,当我尝试在声明的范围之外访问 x 时(在堆上声明),它告诉我 x 未在此范围内声明.
{
int * x = new int;
}
*x = 5; /// Error
我以前从来没有遇到过这个问题。在我调用 delete x;
之前 x 不应该存在吗?
变量x
只能在声明的范围内访问。
无论x
的状态如何,分配的缓冲区一直保留到删除,因此当x
在缓冲区被删除之前和指针存储到[=10=之前变得不可用时,就会发生内存泄漏] 被复制到范围外可用的任何地方。
声明某物与初始化某物不同,事实上:
{
int * x = new int;
}
*x = 5; /// Error
永远不会工作(至少在 C++ 中),但是这个:
int* x;
{
x = new int;
}
*x = 5;
会起作用,因为 x
的声明和使用在同一范围内
x
(一个指针)和它指向的东西(一个 int)是有区别的。
int 不是“在堆上声明的”- 堆不是作用域,也不包含声明。另一方面,x
只是堆栈上的一个普通变量,当其包含块的执行完成时就会消失。
堆上的int
确实继续存在于堆上,但是当你扔掉x
(指针)你就没有办法访问它了,int
已经泄露了。
Why can't access a variable declared with new outside of the scope it was declared in?
因为语言规则说变量名的范围已经结束:
[basic.scope.declarative]
Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity. In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
A name declared in a block ([stmt.block]) is local to that block; it has block scope. Its potential scope begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of its block.
此外,随着名称的范围,对象的生命周期也结束了,因此由变量命名的对象不再存在于块范围之外。
Shouldn't x exist until I call delete x;?
没有。您混淆了具有自动存储的变量 x
和 x
指向的动态对象。动态对象仍然存在,但无法访问,因为您丢失了指针。这种仅指向动态内存的指针的丢失称为内存泄漏。