9

我知道如果您编写 void function_name(int& a),那么函数将不会对作为参数传递的变量进行本地复制。在文献中也遇到过,您应该编写 void function_name(const int & a) 以表示编译器,我不希望复制作为参数传递的变量。

所以我的问题是:这两种情况有什么区别(除了“const”确保传递的变量不会被函数改变!!!)???

4

7 回答 7

11

const当你不需要写的时候,你应该在签名中使用。添加const到签名有两个效果:它告诉编译器您希望它检查并保证您不会更改函数内部的该参数。第二个效果是使外部代码能够使用您的函数传递本身是常量(和临时)的对象,从而可以更多地使用相同的函数。

同时,const关键字是函数/方法文档的重要组成部分:函数签名明确说明您打算对参数做什么,以及传递属于另一个对象的对象是否安全函数中的不变量:您明确表示您不会弄乱他们的对象。

Usingconst在你的代码(函数)中强制了一组更严格的要求:你不能修改对象,但同时对你的调用者的限制更少,使你的代码更可重用。

void printr( int & i ) { std::cout << i << std::endl; }
void printcr( const int & i ) { std::cout << i << std::endl; }
int main() {
   int x = 10;
   const int y = 15;
   printr( x );
   //printr( y ); // passing y as non-const reference discards qualifiers
   //printr( 5 ); // cannot bind a non-const reference to a temporary
   printcr( x ); printcr( y ); printcr( 5 ); // all valid 
}
于 2010-04-28T07:08:42.880 回答
8

所以我的问题是:这两种情况有什么区别(除了“const”确保变量传递不会被函数改变!!!)???

就是区别。

于 2010-04-28T07:05:43.397 回答
1

你说得对。您也可以将其表述为:

如果您想指定函数可以更改参数(即init_to_big_number( int& i )通过(变量)引用指定参数。如有疑问,请指定它const

请注意,不复制参数的好处在于性能,即对于“昂贵”的对象。对于像这样的内置类型int,编写void f( const int& i ). 传递对变量的引用与传递值一样昂贵。

于 2010-04-28T07:09:16.270 回答
1

他们可以操作的参数有很大的不同,假设你有一个来自 int 的类的复制构造函数,

customeclass(const  int & count){
  //this constructor is able to create a class from 5, 
  //I mean from RValue as well as from LValue
}
customeclass( int  & count){
  //this constructor is not able to create a class from 5, 
  //I mean only from LValue
}

const 版本基本上可以对临时值进行操作,而非常量版本不能对临时值进行操作,当您错过需要它的 const 并使用 STL 时,您很容易遇到问题,但是您会收到奇怪的错误,告诉它找不到那个版本暂时需要。我建议尽可能使用 const 。

于 2010-04-28T07:28:53.047 回答
0

它们用于不同的目的。传递变量 usingconst int&可确保您获得具有更好性能的逐个复制语义。您可以保证被调用的函数(除非它使用 做一些疯狂的事情const_cast)不会在不创建副本的情况下修改您传递的参数。int&当一个函数通常有多个返回值时使用。在这种情况下,这些可以用来保存函数的结果。

于 2010-04-28T07:10:42.187 回答
0

我会这样说

void cfunction_name(const X& a);

允许我传递对临时对象的引用,如下所示

X make_X();

function_name(make_X());

尽管

void function_name(X& a);

未能做到这一点。出现以下错误错误:从“X”类型的临时变量中“X&”类型的非常量引用无效初始化

于 2010-04-28T07:46:27.373 回答
0

抛开性能讨论,让代码说话!

void foo(){
    const int i1 = 0;
    int i2 = 0;
    i1 = 123; //i gets red -> expression must be a modifiyble value
    i2 = 123;
}
//the following two functions are OK
void foo( int i ) {
    i = 123;
}
void foo( int & i ) {
    i = 123;
}
//in the following two functions i gets red
//already your IDE (VS) knows that i should not be changed
//and it forces you not to assign a value to i
//more over you can change the constness of one variable, in different functions
//in the function where i is defined it could be a variable
//in another function it could be constant 
void foo( const int i ) {
    i = 123; 
}
void foo( const int & i ) {
    i = 123; 
}

在需要的地方使用“const”有以下好处:*您可以更改一个变量 i 的常量,在定义 i 的函数中的不同函数中,它可以是另一个函数中的变量,它可以是常量值。* 你的 IDE 已经知道我不应该被改变。它迫使你不要给 i 赋值

问候 哎呀

于 2010-04-28T07:55:01.850 回答