在对象的生命周期中,"this"指针的值是否恒定? [英] Is the value of `this` pointer constant during the object's lifetime?
问题描述
在特定对象的生存期内, this
指针的值是否保证是恒定的?我无法想象情况会发生变化,但不知道我是否没有错过任何事情.
Is the value of this
pointer guaranteed to be constant during a lifetime of a particular object? I can't imagine a case where it would change, but don't know whether I am not missing something.
推荐答案
在特定对象的生存期内,
this
指针的值是否保证是恒定的?
Is the value of
this
pointer guaranteed to be constant during a lifetime of a particular object?
是.
以用户 Aconcagua 的说法: this
指针始终是在 1 上调用了该函数的对象的地址值.因此,问题等同于:
As user Aconcagua puts it: the value of this
pointer always is the value of the address of the object on which the function was called on1. So the question is equivalent with:
对象可以在整个生命周期内更改其内存地址吗?
Can an object change its memory address over life time?
根据 lifetime
2 的定义,这是不可能的.对象的生存期从获取对象的时间开始或之后开始,直到释放对象时结束.
This is not possible, by definition of lifetime
2. The lifetime of an object begins when or after its storage is obtained and ends before of when it is released.
在非静态(
[class.mfct]
)成员函数的主体中,关键字this
是 prvalue ,其值是指向要为其调用函数的对象的指针.
In the body of a non-static (
[class.mfct]
) member function, the keywordthis
is a prvalue whose value is a pointer to the object for which the function is called.
2) [basic.life]/1
(重点是我的)
2) [basic.life]/1
(emphasis mine)
对象或引用的生存期是对象或引用的运行时属性.如果变量是默认初始化的,则该变量被称为具有空虚的初始化;如果它是类类型或其(可能是多维)数组,则该类类型具有琐碎的默认构造函数.类型为
T
的对象的生存期始于:
The lifetime of an object or reference is a runtime property of the object or reference. A variable is said to have vacuous initialization if it is default-initialized and, if it is of class type or a (possibly multi-dimensional) array thereof, that class type has a trivial default constructor. The lifetime of an object of type
T
begins when:
- 获得
- 存储,并且具有正确的对齐方式和大小类型
T
的,并且 - 它的初始化(如果有的话)已完成(包括空虚初始化)(
[dcl.init]
),除了如果对象是其并集成员或其子对象,则其生存期仅在联合成员是联合中的初始化成员([dcl.init.aggr]
,[class.base.init]
),或如[class.union]
.
- storage with the proper alignment and size for type
T
is obtained, and - its initialization (if any) is complete (including vacuous initialization) (
[dcl.init]
), except that if the object is a union member or subobject thereof, its lifetime only begins if that union member is the initialized member in the union ([dcl.init.aggr]
,[class.base.init]
), or as described in[class.union]
.
类型为 T
的对象 o
的生存期:
The lifetime of an object o
of type T
ends when:
- 如果
T
是非类类型,则对象被破坏,或者 - 如果
T
是类类型,则析构函数调用开始,或者 - 对象所占用的存储空间已释放,或被未嵌套在
o
([intro.object]
>).
- if
T
is a non-class type, the object is destroyed, or - if
T
is a class type, the destructor call starts, or - the storage which the object occupies is released, or is reused by an object that is not nested within
o
([intro.object]
).
这篇关于在对象的生命周期中,"this"指针的值是否恒定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!