gpt4 book ai didi

C++ `this` 指针

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:47 26 4
gpt4 key购买 nike

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

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

最佳答案

How this pointer is different from other pointers?

this 指针仅存在于非static 类成员函数的上下文中。它也是隐含的,它的名字是一个保留关键字,它总是一个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 分配新地址来改变它是不合逻辑的。从一个对象 move 会 move 对象在别处的状态,但对象本身仍然存在于它之前的地址。

关于C++ `this` 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com