Const and no const in C ++?

I have a program, and many of its classes have some operators and methods with the const keyword, like the following:

operator const char* () const;
operator char* ();
void Save(const char *name) const;
void Load(const char *name);

First: what does it mean that const is at the end of a method declaration ?, is it the same as putting it at the beginning?

Second: why do we need a version of const and do not need a constant operator ()?

Thanks in advance.

+5
source share
8 answers

The 'const' at the end tells the compiler that this method does not change any member variables - it is safe to call this method on const instances. Thus, Save can be invoked on an instance of const, since it will not modify that instance. Loading on the other hand will change the instance, so it cannot be used for const instances.

const () const, , . , . , const, () const. , , .

, 'mutable'. const-correctness.

+2

-: , const ?, , ?

. A const , , const. A const , const.

: const operator()?

a char*, . char*, (, char* ).

const, operator() const, const char*, .

+8

-. , (*) -. - . .

(*) - . mutable.

+2

const , , this const .

++ const . , . .

  • , -, const. - const const .
  • , this const, . , . , .
+1

: operator().

operator const char* () const;
operator char* ();

, , C,

void f(const MyClass& x, MyClass& y) {
  const char* x_str = x;
  char* y_str = y;
}

operator(), , , :

class MyClass {
public:
  const char* operator() (int x, int y) const;
  // ...
};

void g(const MyClass& obj) {
  const char* result = obj(3, 4);
}
+1

++ ( const), " ++".

: JRiddel.org

++, const, , , " - mutable ".

const (, const in: operator const char*...") , const char*. ( char*, .) "const char* const ...", . (const ).

, :

const char* my_const_var = <object_name>();
char* my_var = <object_name>();

+1

, const , " HIGH · INTEGRITY ++ CODING STANDARD MANUAL".

CPR 3.1.8: 'const' - , . (QACPP 4211, 4214)

. , , const , . - ​​const, , . 'mutable' -, const-, , .

class C 
{ 
public: 
     const C& foo() { return * this; }    // should be declared const 
     const int& getData() { return m_i; } // should be declared const 
     int bar() const { return m_mi; }     // ok to declare const 
private: 
int m_i; 
mutable int m_mi; 
};

++ 21: ++ 7.13;

+1
  • . Const . "const", , - - . , , -. . , , . , , .

  • The reason you have two different statements is because the "const" version returns a const pointer to what is probably internal data for the class. If the class instance is constant, then most likely you want the returned data to also be const. The "non-constant" version simply provides a method that returns a modifiable return value when the caller has a non-constant instance of the class.

0
source

All Articles