“this”指针的类型 [英] Type of 'this' pointer
问题描述
如标题中所述,我想知道'this'
指针的类型。
As mentioned in the title, I would like to know about the type of 'this'
pointer.
我正在处理一个项目,我观察到'this'
指针的类型是ClassName * const this
在Windows上使用VC ++ 2008。我想知道什么是需要/要求使这个指针成为一个常量指针。感谢。
I'm working on a project and I observed that the type of 'this'
pointer is "ClassName * const this"
on windows using VC++ 2008. Well I would want to know what is the need/requirement to make the this pointer a constant pointer. Thanks.
推荐答案
此指针的类型是 ClassName *
const ClassName *
,这取决于是否在类 ClassName
的非const或const方法中检查。指针此
不是一个左值。
The type of this pointer is either ClassName *
or const ClassName *
, depending on whether it is inspected inside a non-const or const method of the class ClassName
. Pointer this
is not an lvalue.
class ClassName {
void foo() {
// here `this` has `ClassName *` type
}
void bar() const {
// here `this` has `const ClassName *` type
}
};
上面提到的观察结果是误导性的。指针这个
是不是一个左值,这意味着它不可能有 ClassName * const
类型,即不能在 *
右边有 const
。非指针类型的值不能是const或非const。在C ++语言中根本没有这样的概念。你所观察到的必须是特定编译器的内部怪癖。
The observation you mentioned above is misleading. Pointer this
is not an lvalue, which means that it cannot possibly have ClassName * const
type, i.e. it cannot possible have a const
to the right of the *
. Non-lvalues of pointer type cannot be const or non-const. There's simply no such concept in C++ language. What you observed must be an internal quirk of the specific compiler. Formally, it is incorrect.
以下是语言规范中的相关引用(强调我的)
Here are the relevant quotes from the language specification (emphasis mine)
9.3.2这个指针
在非静态成员函数这是
a prvalue表达式,其值是调用函数的
对象的地址。 这种类型在
的成员函数中,类X是X *。如果成员函数声明为const,那么
的类型为const X *,如果成员函数声明为volatile,那么
类型为volatile X *,如果成员函数声明为
const volatile,其类型是const volatile X *。 [注意:因此在
a const成员函数中,函数调用的对象
通过const访问路径。 -end note]
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 ]
这篇关于“this”指针的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!