通常函数和类在头文件中声明并在一些源文件中定义,例如我有这个函数,它只需要对int进行常量引用并返回bool值来判断参数是偶数还是奇数:
所以在我的标题odd_even.h
我写道:
bool is_even(const int& x); // I used const ref. to avoid copy and unintentional modification of the argument.
在源odd_even.cpp
:
bool is_even(int& x) {
if (x = 1024) // some unintentional assinemnt (==) though modern compilers detect it.
; //some statement here
//x = 1024; // or here another unintentional modification
return !(x % 2) ? true : false;
}
和驱动程序:
int main(){
int a{ 17 };
std::cout << (a) << std::endl;
std::cout << std::boolalpha << is_even(a) << endl;
std::cout << (a) << std::endl;
std::cout << std::endl;
}
正如您所看到的,函数is_even
定义无意中修改了参数,并且我的程序的客户端没有意识到该函数将修改参数,只要其声明采用const引用int。
那么有关于这个错误的解决方法可以防止这样的错误吗?
这不应该像here那样编译
当参数是指针或引用类型时,C ++允许cv限定符重载,因此它是受损名称的一部分。
这里没有top-level const
:
bool is_even(const int& x); // 1
bool is_even(int& x); // 2
高于1和2的是完全不同的签名:1是一个对int进行常量引用的函数。请记住const
这里是low-level
而不是top-level
还要记住,引用没有顶级const作为它们已经不变的事实。
在您的示例中,它编译并运行正常,因为您传递的是与签名2相关的非const对象。但是,如果传递r值或者它将无法链接。例如:
std::cout << is_even(77) << std::endl; // link will fail because the 1 is not defined.