联系
Knight's Tale » 技术

Summary on "const" in C++

2010-06-01 22:27

"const"  is a very common key word in C++ programming language. I use lots of "const" in my previous project and now I want to write some summary about the usage of it.

I suppose there is a Class "A".

  • const with "Pointer"
    1. const A * a :  it's a pointer to const class A. You can change the pointer a, but you cannot change the data it points to.
    2. A const *a :   it's the same to the usage of 1.
    3. A * const a:  it's a constant pointer to class A. You can change the data pointer a points to , but you can change the pointer.
  • const with "Call by reference"
    1. const A &a: object a cannot be modified.
    2. A const &a:  it's the same to the usage of 1.
    3. A & const a:  It's a not recmmended usage! ( visual studio: warning C4227: anachronism used : qualifiers on reference are ignored!)
  • const with normal usage
    1. const int i;
    2. int const i;
    the usage of 1 and 2 is the same.
One Example:
class A
{
public:
    int val;
};

void test1( A & const a) { A aa; aa.val = 2; a = aa; // warning C4227: anachronism used : qualifiers on reference are ignored }

void test2(const A & a) { A aa; aa.val = 3; a = aa; // error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const A' (or there is no acceptable conversion) }

void main() { A aa; test1(aa); test2(aa);

A aaa;
aaa.val =4;
A & const bbb=aaa;   // warning C4227: anachronism used : qualifiers on reference are ignored

}

Thanks!

Reference:

[1]. http://www.devmaster.net/forums/archive/index.php/t-3863.html [2]. http://faq.csdn.net/read/2143.html

本文链接地址:Summary on "const" in C++