mercredi 21 février 2018

What about pseudoconst qualifier

Imagine a class has two "const opposite" methods, non const, but which called one after the other leave the object unchanged. Another method starting with a call of the two const opposite method, calling const methods, and then the opposite const method of the couple... Well, this method is non const but left the object unchanged. Compilers may call it pseudoconst (and enforce only const methods or pseudo const methods are called between couples of const opposite methods) ?

Maybe, an example will be clearer

#include <vector>

class Vec {
public : 
  Vec () : val_ (std::vector<size_t> (1000, 0)) {}
  Vec (const Vec& v) : val_ (v.val_) {}
  ~Vec () {}
  //couple of const opposite methods
  void inc () {
    std::for_each (val_.begin (), val_.end (), [] (size_t&s) {++s;});
  }
  void dec () {
    std::for_each (val_.begin (), val_.end (), [] (size_t&s) {--s;});
  }

  void write2 (std::ostream& os) const {
    os << "val_ [2] == " << val_ [2] << std::endl;
  }
  void write_next2const (std::ostream& os) const {
    Vec v (*this);
    v.inc ();
    v.write2 (os);
  }
  void write_next2pseudoconst (std::ostream& os) { //pseudo const method
    inc ();
    write2 (os);
    dec ();
  }
//private :
  std::vector<size_t> val_;
};

test program :

int main (int argc, char* argv []) {
  size_t duration (0);
  clock_t t (clock ());
  Vec v;
  v.write_next2const (std::cout);
  duration = (clock() - t);
  std::cout << "write_next2const took " << duration << " ticks" << std::endl;
  t = clock ();
  v.write_next2pseudoconst (std::cout);
  duration = (clock() - t);
  std::cout << "write_next2pseudoconst took " << duration << " ticks" << std::endl;
  return 0;
}

shows that pseudoconst method is much faster :

val_ [2] == 1
write_next2const took 124 ticks
val_ [2] == 1
write_next2pseudoconst took 3 ticks

but the second could not be declared const though leaving the objects unchanged. What about "pseudoconst" qualifier in next compilers ?

Aucun commentaire:

Enregistrer un commentaire