2011年10月25日 星期二

容易混淆的const with point

const宣告的變數,被const宣告的變數一但被指定值,就不能再改變變數的值,您也無法對該變數如下取值:

const int var = 10;
var = 20; // error, assignment of read-only variable `var'
int *ptr = &var; // error,  invalid conversion from `const int*' to `int*'


用const宣告的變數,必須使用對應的const型態指標才可以:

const int var = 10;
const int *vptr = &var;

同樣的vptr所指向的記憶體中的值一但指定,就不能再改變記憶體中的值,您不能如下試圖改變所指向記憶體中的資料:

*vptr = 20; // error, assignment of read-only location

另外還有指標常數,也就是您一旦指定給指標值,就不能指定新的記憶體位址值給它,例如:

int x = 10;
int y = 20;
int* const vptr = &x;
vptr = &x;  // error,  assignment of read-only variable `vptr'

在某些情況下,您會想要改變唯讀區域的值,這時您可以使用const_cast改變指標的型態,例如:



#include <iostream> 
using namespace std; 

void foo(const int*); 
 
int main() { 
    int var = 10; 
 
    cout << "var = " << var << endl; 
 
    foo(&var); 
 
    cout << "var = " << var << endl; 
 
    return 0; 
}

void foo(const int* p) {
    int* v = const_cast<int*> (p); 
    *v = 20; 
}


由於函式(Function)定義中傳入的指標使用const加上唯讀性,所以您不能對傳入的指標進行以下的動作:

*p = 20; // error, assignment of read-only location

但在某種原因下,您真的必須改變指標指向的位址處之資料,則您可以使用const_cast改變指標的唯讀性,

int* v = const_cast<int*> (p);
*v = 20;

執行結果:


var = 10
var = 20


您也可以使用舊風格的轉型語法,例如:

void foo(const int* p) {
    int* v = (int*) (p);
    *v = 20;
}



// Attempting to modify a constant pointer to nonconstant data.


int main()
{
      int x, y;
                // ptr is a constant pointer to an integer that can
                // be modified through ptr, but ptr always points to the
                // same memory location.
                int * const ptr = &x; // const pointer must be initialized
      *ptr = 7; // allowed: *ptr is not const
      ptr = &y; // error: ptr is const; cannot assign to it a new address
} // end main
// Attempting to modify a constant pointer to constant data.
#include <iostream>
using namespace std;


int main()
{
     int x = 5, y;


     // ptr is a constant pointer to a constant integer.
     // ptr always points to the same location; the integer
     // at that location cannot be modified.
     const int *const ptr = &x;


     cout << *ptr << endl;


     *ptr = 7; // error: *ptr is const; cannot assign new value
     ptr = &y; // error: ptr is const; cannot assign new address



} // end main