`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?

.

正如用户Aconcagua所说:this指针的值始终是调用函数的对象的地址值在1。所以这个问题等同于:

Can an object change its memory address over life time?

根据 lifetime2 的定义,这是不可能的。对象的生命周期从获得其存储时或之后开始,到释放之前结束。


1) [class.this]/1

In the body of a non-static ([class.mfct]) member function, the keyword this is a prvalue whose value is a pointer to the object for which the function is called.

2) [basic.life]/1(强调我的)

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:

  • 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].

The lifetime of an object o of type T ends when:

  • 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 指向那里。

[intro.object]/1

An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime, and in its period of destruction ([class.cdtor]).

this 的值保证是常量,如果程序曾经读取它,如果随后读取值的某些位不可能被垃圾收集,或者如果随后读取值的某些位在该程序。在所有其他情况下,它的行为就像薛定谔的猫,也就是说,它既是常数又是变量。