简体   繁体   中英

Reference functions in C++

I have a function that gives me the error "cannot convert from 'int' to 'int &'" when I try to compile it.

int& preinc(int& x) { 
    return x++;
}

If I replace x++ with x, it will compile, but I'm not sure how that makes it any different. I thought that x++ returns x before it increments x, so shouldn't "return x++" be the same as "return x" with regard to what preinc returns? If the problem is with the ++ operator acting on x, then why won't it generate any error if I put the line "x++" before or after the return statement, or replace x++ with ++x?

x++ creates a temporary copy of the original, increments the original, and then returns the temporary.

Because your function returns a reference, you are trying to return a reference to the temporary copy, which is local to the function and therefore not valid.

Your function does two things:

  • Increments the x that you pass in by reference
  • Returns a reference to the local result of the expression x++

The reference to a local is invalid, and returning anything at all from this function seems completely redundant.

The following is fixed, but I still think there's a better approach:

int preinc(int& x) {
   return x++; // return by value
}

Yes, x++ returns x before it is incremented. Therefore it has to return a copy, the copy is a temporary and you can only pass temporaries as constant references.

++x on the other hand returns the original x (although incremented), therefore it will work with your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM