C++:将函数参数定义为const T的意义
C++很多函数的参数都会定义为const T&,那么这么做的意义是什么呢?
-
避免拷贝:通过引用传递参数而不是值传递,可以避免对象的拷贝,从而提高性能,特别是当对象较大时。
-
保护数据:使用
const
关键字可以防止函数修改传入的参数,确保数据的安全性和一致性。
对于保护数据这里比较明显,不必说明,我们来看一下避免拷贝:
#include <iostream>
#include <string>
using namespace std;
class MyData{
public:
MyData(const char* s)
{
cout<<"MyData construct:"<<s<<endl;
}
MyData(const MyData& m)
{
cout<<"MyData copy construct"<<endl;
}
};
void doTest1(const MyData& m)
{
}
void doTest2(MyData m)
{
}
int main()
{
doTest1("hello1");
doTest2("hell