the usage of keyword const
来源:互联网 发布:大数据产品经理面试题 编辑:程序博客网 时间:2024/05/18 01:45
1. define the const constant for example: const int a
2. define the const parameter of function int Max(const int a, const int b)
如果输入参数采用"指针传递",那么加const修饰可以防止意外地改动该指针,起到保护作用。
例如StringCopy函数:
void StringCopy(char *strDestination, const char *strSource);
如果输入参数采用"值传递",由于函数将自动产生临时变量用于复制该参数,该输入参数本来就无需保护,所以不要加const修饰。
例如不要将函数void Func1(int x) 写成void Func1(const int x)。同理不要将函数void Func2(A a) 写成void Func2(const A a)。其中A为用户自定义的数据类型。
对于非内部数据类型的参数而言,象void Func(A a) 这样声明的函数注定效率比较
底。因为函数体内将产生A类型的临时对象用于复制参数a,而临时对象的构造、复制、析构过程都将消耗时间。
为了提高效率,可以将函数声明改为void Func(A &a),因为"引用传递"仅借用一下参数的别名而已,不需要产生临时对象。但是函数void Func(A &a) 存在一个缺点:"引用传递"有可能改变参数a,这是我们不期望的。解决这个问题很容易,加const修饰即可,因此函数最终成为void Func(const A &a)。
以此类推,是否应将void Func(int x) 改写为void Func(const int &x),以便提高效率?完全没有必要,因为内部数据类型的参数不存在构造、析构的过程,而复制也非常快,"值传递"和"引用传递"的效率几乎相当。
问题是如此的缠绵,我只好将"const &"修饰输入参数的用法总结一下,如表。
对于非内部数据类型的输入参数,应该将"值传递"的方式改为"const引用传递",目的是提高效率。例如将void Func(A a) 改为void Func(const A &a)。
对于内部数据类型的输入参数,不要将"值传递"的方式改为"const引用传递"。否则既达不到提高效率的目的,又降低了函数的可理解性。例如void Func(int x) 不应该改为void Func(const int &x)。
3. the const function return value const int Find(int num)
- the usage of keyword const
- The Usage of the volatile Keyword
- The const keyword
- The instance of keyword
- The usage of finalize()
- usage of the serialVersionUID
- the usage of lucene
- The usage of SQLPATH
- the usage of sscanf()
- the usage of vim
- The usage of #pragma
- The usage of InjectView
- native, The Keyword Of Java
- Usage of the vc timer
- The Usage of map::insert
- The Usage of Java Timer
- the usage of android viewpage
- The usage of V$PGA_TARGET_ADVICE
- linux 如何对库和可执行文件进行裁减
- servlet中判断JSP中按钮问题
- 编程回忆之Android回忆(Android 调用短信服务)
- 谈谈策略
- GetLastError 和 FormatMessage搭配使用的模板
- the usage of keyword const
- 读书笔记_Rootkit技术_文件过滤驱动程序(1)
- yuntable master代码阅读
- SQL Server自动增长列重置
- 内存对齐
- maven常见问题问答
- 自动锁定电脑设置
- Dalvik虚拟机和一般JAVA虚拟机(Java VM)不同
- 新的开始,从头再来