简体   繁体   English

'this'类型为“Class * const”,即使方法不是const

[英]'this' of type “Class* const” even though method is not const

Today I noticed something strange about the type of 'this'. 今天我注意到'this'的类型有些奇怪。 If you have something like this: 如果您有这样的事情:

class C {
    void funcA() {
        funcB(this);
    }

    void funcB(C obj) {
        //do something
    }
};

You will of course get an error, because funcB() expects an object, while 'this' is a pointer. 你当然会得到一个错误,因为funcB()需要一个对象,而'this'是一个指针。 I accidentally did forget the asterisk, but was surprised by the error message, as it said: 我不小心忘记了星号,但对错误信息感到惊讶,因为它说:

no matching function for call to 'C::funcB(C* const)'

Where does the const come from, when funcA() is not constant? 当funcA()不是常数时,const来自何处?

That's saying that the this pointer itself as const -- ie, you can't modify the pointer to point to different memory. 那就是说this指针本身就是const - 即你不能修改指针指向不同的内存。

Back in the very early history of C++, before you could overload new and delete , or placement new was invented, this was a non-const pointer (at least inside the ctor). 早在C ++的早期历史,之前,你可以重载newdelete ,或放置新的发明, this是一个非const指针(至少在构造函数中)。 A class that wanted to handle its own memory management did so by allocating space for an instance in the constructor, and writing the address of that memory into this before exiting the constructor. 想要处理自己的内存管理的类通过在构造函数中为实例分配空间,并在退出构造函数之前将该内存的地址写入this

In a const member function the type you'd be dealing would be Class const *const this , meaning that what this points at is const (as well as the pointer itself being const ). 在一个const成员函数你会处理的类型将是Class const *const this ,这意味着什么this点在为const (以及指针本身是const )。

C* const does not mean that the object of type C is constant. C* const并不意味着C类型的对象是常量。 That would be C const* or const C* . 那将是C const*const C*

C* const means that the pointer itself is constant. C* const表示指针本身是常量。

Which makes sense, since you cannot do 这是有道理的,因为你做不到

this = &something_else;

Note that it's not C const * , but C* const . 请注意,它不是C const * ,而是C* const Ie (reading from right to left) constant pointer to C . 即(从右到左阅读)指向C常量指针。

There is a difference between C const* and C * const . C const*C * const之间存在差异。 You need to understand the difference: 你需要了解区别:

  • C const* means it is the object (pointed to by the pointer) which is constant. C const*表示它是对象(由指针指向)是常量。
  • C * const means it is the pointer itself which is constant. C * const表示指针本身是常量。

So this by definition is a pointer of C * const type, so it cannot be modified, though the object pointed to by it can still be modified. 因此,根据定义, this是一个C * const类型的指针,因此它不能被修改,尽管它所指向的对象仍然可以被修改。

指针本身是常量,而不是指向的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM