struct MyData {
int a,b,c,d,e,f,g,h;
long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);
When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If you are using const reference, you pass it by reference and the original data is not copied.
int a;
void DoWork(const int &n)
{
a = n * 2; // If n was a reference to a, n will have been doubled
f(); // Might change the value of whatever n refers to
}
int main()
{
DoWork(a);
}
此外,如果传入的对象实际上不是 const,那么函数可以(即使不明智)通过强制转换更改其值。
例如:。
void DoWork(const int &n)
{
const_cast<int&>(n) = 22;
}
This would cause undefined behaviour if the object passed in was actually const.
Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.
$8.3.2/1-“ Cv 限定的参考资料格式不正确,除非
cv-qualifiers are introduced through the use of a typedef (7.1.3) or
of a template type argument (14.3), in which case the cv-qualifiers
都被忽略了”
Here are the differences
$13.1 - "Only the const and volatile type-specifiers at the outermost
以这种方式忽略参数类型规范的级别;
常量和易失性类型说明符隐藏在参数类型中
规格是有意义的,可以用来区分
重载的函数声明。112)特别是,对于任何类型 T,
“指向 T 的指针”、“指向常量 T 的指针”和“指向易失性 T 的指针”是
被认为是不同的参数类型,如“引用 T”,
“引用常量 T”和“引用挥发性 T”
void f(int &n){
cout << 1;
n++;
}
void f(int const &n){
cout << 2;
//n++; // Error!, Non modifiable lvalue
}
int main(){
int x = 2;
f(x); // Calls overload 1, after the call x is 3
f(2); // Calls overload 2
f(2.2); // Calls overload 2, a temporary of double is created $8.5/3
}