gpt4 book ai didi

c++ - 'this' 指针的类型

转载 作者:IT老高 更新时间:2023-10-28 12:43:06 26 4
gpt4 key购买 nike

正如标题中提到的,我想知道 'this' 指针的类型。

我正在做一个项目,我观察到 'this' 指针的类型是 "ClassName * const this" 在使用 VC++ 2008 的 Windows 上。好吧,我想知道使 this 指针成为常量指针的需要/要求是什么。谢谢。

最佳答案

这个指针的类型是ClassName *const ClassName * ,取决于是在类 ClassName 的非 const 或 const 方法中检查它.指针 this不是左值。

class ClassName {
void foo() {
// here `this` has `ClassName *` type
}

void bar() const {
// here `this` has `const ClassName *` type
}
};

您上面提到的观察结果具有误导性。指针 this 不是左值,这意味着它不可能有ClassName * const类型,即不可能有 const * 的右侧.指针类型的非左值不能是 const 或非常量。 C++ 语言中根本没有这样的概念。您观察到的一定是特定编译器的内部怪癖。形式上是不正确的。

以下是语言规范中的相关引用(重点是我的)

9.3.2 The this pointer

In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*. [ Note: thus in a const member function, the object for which the function is called is accessed through a const access path. —end note ]


在 C++98/C++03 时代,几个编译器使用了一个内部实现技巧,这是毫无值(value)的:他们解释了他们的 this指针作为常量指针,例如ClassName *const在类 ClassName 的非常量方法中.这显然有助于他们确保 this 的不可修改性。 .众所周知,GCC 和 MSVC 已经使用了该技术。这是一个无害的技巧,因为在语言级别 this不是左值,它的常数是不可检测的。那个额外的const通常只会在编译器发出的诊断消息中显示自己。

然而,随着 C++11 中右值引用的出现,检测到这个额外的 const 成为可能。关于 this 的类型.例如,以下代码在 C++11 中有效

struct S
{
void foo() { S *&&r = this; }
};

然而,它通常无法在仍然使用上述技巧的实现中编译。 GCC 已经放弃了这项技术。 MSVC++ 仍然使用它(自 VS2017 起),这会阻止上述完全有效的代码在 MSVC++ 中编译。

关于c++ - 'this' 指针的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067244/

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