'const'에 해당되는 글 1건

  1. 2009.03.11 [C/C++] 'const' keyword.

[C/C++] 'const' keyword.

Language/C&C++ 2009.03.11 22:28
[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

Using 'const' wherever possible is very very important. It can help to avoid mistakes and increase readability very much.
Personally, I even regard ability of using 'const' in code, as one of most important evidence to evaluate programmer's quality.

==== const member function ====

class A {
    void funcB(void) const;
    void funcA(int* pa) const;
    int* funcC(void) const;
    int a
}

const member function(henceforth const member) cannot change class member variable. And, const member can call only const member. But, const member can call any C function.
By the way, there is no constraints about parameter in const member. So, following is possible.

Hack 1
  void A::funcB(void) const { funcA(&a); }
  void A::funcA(int* pa) const { *pa = 9; }

Hack 2
  void A::funcB(void) const ( int* p = funcC(); *p = 8; }
  int* A::funcC(void) const {return &a;}

Even if, funcB changes value of member variable, it compiles well. This is one of week points of const member.

==== const & pointer ====

const int* p;   // *1 - (*p) is const
int const *p;   // *2 - (*p) is const
int* const p;   // *3 - (p) is const

case *1, *2;

"*p = 4" is error, but, "p = &b" is OK.
So, we can hack this like "*((int*)p) = 9;".

case *3

contrary to upper case. So, we should initialize pointer before using it.

==== const & multiple pointer ====

const int** p;   // *1
int const **p;   // *2
int* const *p;   // *3
int** const p:   // *4

int*       pb;
const int* cpb
int b;

case *1, *2.

// p = &pb; // error - "cannot convert from 'int **' to 'const int **"
p = &cpb; // OK.
*p = &b;
// **p = 8; // error - "you cannot assign to a variable that is const"
*((int*)*p) = 8 // OK. Hack!

case *3

p = &pb; // OK
*p = &b; // error - "you cannot assign to a variable that is const"

case *4

p = &pb; // error - "you cannot assign to a variable that is const". p should be initialized before used.

신고
tags : ,
Trackback 0 : Comment 0

티스토리 툴바