简体   繁体   中英

const-correctness for this and member functions

assuming that I have a generic class A

class A {
  ...
  int a;                // a member
  void foo() const{...} // a member function qualified as const
  ...
};

this implies that if I declare an instance of A like A k; and then I call k.foo(); the this pointer that is acting on/inside that call to foo is something of type const A * const .

Now I would like to know why the code in this blog post works, especially about why this doesn't apply to global variables.

My explanation is about an hidden operation about pointer aliasing, like the this pointer being copied implicitly and during this copy the result is not const anymore ( for some reason ... ) but it's still a this pointer meaning that is a pointer to the same instance.

My question is about: what really const does if it's applied after the declaration of an interface for a member function ? Do you have a specific answer for the linked blog post ?


code from the blog

#include <iostream>

class counter {
public:
  int i;    
  counter();    
  int inspect() const;
  void increment();
};

counter sigma_inspect; // sigma_inspect is global

counter::counter() { i = 0; }

int counter::inspect() const {
  sigma_inspect.increment();
  return i;
}

void counter::increment() {
  ++i;
  return;
}

int main(void) {
  counter a; 
  std::cout << a.inspect() << "\n"; 
  std::cout << sigma_inspect.inspect() << "\n";
  std::cout << sigma_inspect.inspect() << "\n";
  return 0;
}

The call in the blog post is using sigma_inspect which is non-const and it is calling a non-const method on it instead of calling said method through the const this pointer. So what? The author seems to expect magic instead of the obvious of what he wrote. It's like having

T* t = ...;
const T* ct = t;
t->foo(); // foo() is not const, but hey,
          // I also have a const pointer now (ct),
          // so why can I still use this???

Generally, if someone calls C++ stupid it tells you more about the author instead of the language :)

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