pointer
T const * p ó const T * p;
T * const p;
T const * const p ó const T * const p;
Character array literal.
Char* p = "kaven";
P[1] = 'A'; //no compile time error! But will got runtime error!!
Const char* cp = "kaven";
Cp[1] = 'A'; //compile error!!
Char ap[] = "kaven";
Ap[1] = 'A'; //ok!
・ Character array literals "kaven" is created by the compiler as a constant character array .
・ So suggest that use const char* if you don't want it to be changed.
・ If you want to be able to modify the string ,put it in array: char ap[];
Assignment and type cheching
Int d = 1;
Const int e = 2;
Int* pd = &d; //ok!
Int* pe = &e; //error! Can not assign the address of a const object to a non-const pointer.
//because you are saying you might change the object via the pointer.
Int const *cp = &e; //ok now.
Int * const cp = &e; //error too.
Int* pe = (int*)&e; //illegal but bad practice.
・ You can assign the address of a non-const object to a const pointer.
・ But you can't assign the address of a const object to a non-const pointer!
Function
Const T func( const T& a) const;
让函数返回一个常量值经常可以在不降低安全性和效率的情况下减少用户出错的几率,防止对返回值进行赋值或修改.
const T& a) const;
const成员函数的目的当然是为了指明哪个成员函数可以在const对象上被调用。
个成员函数为const的确切含义是什么?
bitwise constness的坚持者认为,当且仅当成员函数不修改对象的任何数据成员(静态数据成员除外)时,即不修改对象中任何一个比特(bit)时,这个成员函数才是const的。
尽量用"传引用"而不用"传值"
消除一些对拷贝构造函数的调用
避免了所谓的"切割问题(slicing problem)"。
引用几乎都是通过指针来实现的,所以通过引用传递对象实际上是传递指针。因此,如果是一个很小的对象――例如int――传值实际上会比传引用更高效。
No comments:
Post a Comment