简体   繁体   中英

About const_cast usage in cppreference

Please refer to this page and go down to the Example. This is a demonstration about usage of

struct type {
    type() :i(3) {}
    void m1(int v) const {
      // this->i = v;                 // compile error: this is a pointer to    const
      const_cast<type*>(this)->i = v; // OK as long as the type object isn't const
  }
   int i;
};

const here means that m1 could not modify type's member variables. I can't understand why const_cast modify the constness of this . I mean, this pointer points to current type object, not the i itself.

Why not:

const_cast<int>((this)->i) = v; 

May I say when one of member function use a const qualifier, the whole object and all member variables become const ? Why this is const pointer?

I can't understand why const_cast modify the constness of this

It doesn't. You could say it creates another temporary pointer, which is not a pointer to a const type , but contains the same address as this . It then uses that pointer to access i .

Why not const_cast<int>((this)->i)

You could do something like this, but you need a cast to a reference, not a plain integer.

const_cast<int&>(i) = v; // this-> omitted for brevity

Same caveats apply as any modification of i if this points at an object that is really const.

May I say when one of member function use a const modifier, the whole object and all member variables become const? Why this is const pointer?

Yes. The const qualifier on the member function means that this 's pointee type is type const . And all members (which are not mutable) are also const for any access via this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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