How can I find C ++ functions that should be const?

I have this code:

#include <stdio.h>

class A
{
public:
  int doit()
  {
    return 5;
  }
  int doit2() const
  {
    i++;
    return i;
  }
  int i;
};

int main()
{
  A a;
  printf("%d\n", a.doit() );
  return 0;
}

Which compiles with g ++ -Wall -Wpedantic main.cpp. Is there a way to get g ++ to say: "A :: doit () should be marked as const"? g ++ 4.8 has -Wsuggest-attribute = const, but in this case it does not work. g ++ -Wall -Wpedantic -Wsuggest-attribute = const const_main.cpp -fipa-pure-const -O2 -Wextra is still clean.

, const - , , , - , , , , const . , , , const, , . , const const, , , , .

non-const doit2(), const, :

const_main.cpp: In member functionint A::doit2() const’:
const_main.cpp:12:6: error: increment of memberA::iin read-only object
     i++;
      ^

( , const, ).

: ++

+4
3

. , - , . gcc , doit() const, const... . , , -, .

- ala throw Not_Implemented(); - throw const, , , const. std::string::shrink_to_fit() - - , , const, ( , ), const, (, , resize()).

+5

++, const?

, this (class) . , , - , const.

: , , const , , .

+1

non-const doit2(), const, : 'A::

This is because you are trying to change a member variable inside a function const. A function constis a pure observer function that does not change the state of an object and, therefore, when trying to change the state in such a function, the compiler complains.

Inside a function, constall member variables, whether declared constor not, will have a qualifier const. An exception to this rule is declared mutable.

0
source

All Articles