const定义常量
const 定义常量意味着只读,c++中的const常量类似于#define,但又不同,const常量是由编译器处理的,而宏定义是在预处理阶段处理。
const int a = 3;
int const a = 3;
以上两种定义等价,都代表一个常整形
const修饰指针
const int* a; //指针a所指向内存数据是不可以修改的,但指针本身是可以改变的
int* const a; //指针变量a是不可以被修改的,但a指向的内存数据确是可修改的
const int* const a; //指针本身不可以被修改,指向的内存数据也不可以被修改
const 修饰形参的时候,在利用形参不能修改指针指向的内存
合理利用const的好处:
1.可以提高代码的可读性,减少bug
2.清楚的分清参数的输入和输出,有const修饰的肯定是传入了
const 引用
const 引用的的目的是,禁止通过修改引用值来改变被引用的对象。
看一段代码先:
int a = 3;
const int &b = a;
b = 4; //会失败
a = 6; //ok
cout << b << endl; //此时b=6
常引用是只读的,因此不能通过给b赋值来改变a。但通过改变a却可以改变b的值。常引用在编写函数时经常用到,可以通过常引用让实参变量拥有只读属性,这样可以防止在函数内部的误操作改变了原本的值。
const 引用的特性:
1>const 对象的引用必须是const
2>const 引用可使用相关类型的对象初始化
const 位于函数之后
virtual int Compare() const = 0;
上面这段代码表示了const位于函数的后面这种情形。
加const表明这个函数是只读的,不允许在函数的内部修改类的成员变量(非静态成员变量),告诉你这个成员不会修改对象的状态,提高了安全性。
原理:
给隐含的this指针加const(类似 const 类名* this ),表明this所指向内存空间是不可修改的,也就是这个对应对象中的成员变量(非静态成员变量)是不可修改的。
那为什么静态成员变量确是可以修改的?那是因为静态成员变量位于全局数据区,而不在该对象的内存空间中,this指针管不着它。
总而言之,善用const 对提高代码的可读性和安全性很重要,要多看多练
贴一段google的代码,真漂亮!!!
namespace leveldb {
class Slice;
// A Comparator object provides a total order across slices that are
// used as keys in an sstable or a database. A Comparator implementation
// must be thread-safe since leveldb may invoke its methods concurrently
// from multiple threads.
class LEVELDB_EXPORT Comparator {
public:
virtual ~Comparator();
// Three-way comparison. Returns value:
// < 0 iff "a" < "b",
// == 0 iff "a" == "b",
// > 0 iff "a" > "b"
virtual int Compare(const Slice& a, const Slice& b) const = 0;
// The name of the comparator. Used to check for comparator
// mismatches (i.e., a DB created with one comparator is
// accessed using a different comparator.
//
// The client of this package should switch to a new name whenever
// the comparator implementation changes in a way that will cause
// the relative ordering of any two keys to change.
//
// Names starting with "leveldb." are reserved and should not be used
// by any clients of this package.
virtual const char* Name() const = 0;
// Advanced functions: these are used to reduce the space requirements
// for internal data structures like index blocks.
// If *start < limit, changes *start to a short string in [start,limit).
// Simple comparator implementations may return with *start unchanged,
// i.e., an implementation of this method that does nothing is correct.
virtual void FindShortestSeparator(std::string* start,
const Slice& limit) const = 0;
// Changes *key to a short string >= *key.
// Simple comparator implementations may return with *key unchanged,
// i.e., an implementation of this method that does nothing is correct.
virtual void FindShortSuccessor(std::string* key) const = 0;
};
// Return a builtin comparator that uses lexicographic byte-wise
// ordering. The result remains the property of this module and
// must not be deleted.
LEVELDB_EXPORT const Comparator* BytewiseComparator();
} // namespace leveldb