C++ `this` 指针

C++ `this` pointer

1) this 指针与其他指针有何不同?据我了解,指针指向堆中的内存。这是否意味着对象总是在堆中构造,因为有指向它们的指针?

2)我们可以在移动构造函数或移动赋值中窃取this指针吗?

How this pointer is different from other pointers?

this 与其他指针没有什么不同,除了你不能改变它的值并且它只存在于成员函数中。是保留关键字。

As I understand pointers point to the memory in heap. Does that mean objects are always constructed in heap, given that there is pointer to them?

不,指针(有效或无效)可以指向 "anywhere"。不,structs/classes 可以分配到任何地方。在自动存储(堆栈)上,在自由存储(堆)上,如果平台支持,则在其他地方。

Can we steal this pointer in move constructor or move assignment?

不太确定你在问什么,但答案很可能是否定的。

How this pointer is different from other pointers?

this 指针仅存在于非static class 成员函数的上下文中。它也是隐含的,它的名字是一个保留关键字,它总是一个prvalue expression。否则,它与任何其他指针相同。

As I understand pointers point to the memory in heap.

指针可以指向内存中的任何东西。它不仅限于堆,也不限于堆 objects.

Can we steal this pointer in move constructor or move assignment?

this 始终是纯右值表达式。无法为其分配新地址,就像您无法为 5 分配新值一样。事实上,对象在其整个生命周期中都存在于内存中的一个位置。他们的地址永远不会改变,试图通过为 this 分配新地址来改变它是不合逻辑的。从对象移动会移动对象在其他地方的 valuestate,但对象本身仍然存在于它以前的地址。

1) How this pointer is different from other pointers?

this是关键字。它不能也不需要声明。 this 在 non-static 成员函数中隐式可用。 this引用成员函数的实例参数。

相反,指针变量可以而且通常需要声明。指针声明的例子:

void* ptr = nullptr;

As I understand pointers point to the memory in heap.

你误会了。指针不限于只指向堆1.

Does that mean objects are always constructed in heap

鉴于你的前提是错误的,这个问题的答案仍然是否定的。对象不限于只能在he​​ap1中构造。这是一个例子:

void foo() {
    int i;
    int* iptr = &i;
}

该示例有两个对象,它们都具有自动存储(即不是动态存储,即不是堆1)。其中一个是整数,另一个是指向整数的指针。请注意,指针不指向 heap1.


2)Can we steal this pointer in move constructor or move assignment?

取决于您所说的 "steal" 是什么意思。但可能没有。


1 C++语言没有"heap"内存的概念。您可能指的是动态存储或免费存储。