记得读Effective c++时,有一个tips,尽可能多的使用const(Use const whenever possible)
我在项目中用的比较多的情况有:
- 定义常量对象
- 基于范围的 for 循环我一般使用常量引用的方式(不修改元素情况)
- 配合const+& 做参数传递 const parameter
- const函数 const function
- const返回值 const return value
- const 修饰指针
1.常量对象定义
#define PI=3.1415926;
const double PI_ = 3.1415926;
2. 基于范围的for循环我一般使用常量引用的方式(不修改元素)
std::vector<int> nums{ 1,2,3,4 };
int sum = 0;
for(const auto& num:nums){
sum += num;
}
3. 函数传递时我喜欢用引用(有的人喜欢用指针)
我通过加不加const来标示,
- 对于不修改的情况下通过const+&的方式
int calVecSum(const std::vector<int>& nums){
int sum = 0;
for (const auto& num : nums) {
sum += num;
}
return sum;
}
- 通过参数作为返回值时,通过引用
void calVecSum(const std::vector<int>& nums,int& sumOut){
for (const auto& num : nums) {
sumOut += num;
}
}
//当然也可以用指针,我比较喜欢用引用
void calVecSum1(const std::vector<int>& nums, int* sumOut) {
for (const auto& num : nums) {
*sumOut += num;
}
}
const 再传递参数时不和&配合的话,跟不加没区别
//加不加const的意思是一样的
void SetAge(int a) {age = a;}
void SetAge(const int a) {age = a;}
//error: has already been defined
4.const 函数
const funtion means this function will note change any of the member variabes of this class
有点类似c# 的get属性器,增加const后,不修改成员变量数据,也不能调用非const函数,提高程序的健壮性
- note:const成员函数可以调用静态成员变量及静态成员函数
class CPoint2D{
public:
CPoint2D():x(0),y(0){}
static int index;
double x;
double y;
void SetX(double value) { x = value; }
double GetX() const {
y = 3 ; //错误,修改成员变量
SetX(3) ; //错误,调用非const函数
index = 1; //ok
return x;
}
double GetY() const { return y; }
};
5. const return value
- 注意下文函数中去掉&后,const就完全没有作用了, because the name is returned by value. what the function returned is copy of name which is a temporary
class Dog {
public:
std::string name;
//const return value
const std::string& getName() {return name;}
//注意去掉&
const std::string getNanme{return name;}
};
6. const with pointer
- if const is on the left of*, data is const
- if const is on the right of *,pointer is const
int i = 9;
const int *p1 = &i; //data is const, pointer is not
int* const p2=new int; //pointer is const, data is not
const int* const p3=new int; //data and pointer are both const
下面是一样的
// there are the same ,they are both on the left of *
int const *P4=&i;
const int *p4=&i;
const 好处
// const has several benefits
// a.) Guards against inadvertent write to the variable, so it can stop the wrong behavior at
// b.) Const is a way of self documenting, tell the reader this value will not be changed
// c.) Enables compiler to do more optimization, make the code tighter & faster
// d.) const means the variable can be put in rom (read-only memory)
待续...
参考:
默然:C++笔记 · C++关键字 - constzhuanlan.zhihu.com