简体   繁体   English

当我返回传递给函数的引用参数时,内部会发生什么?

[英]What happens internally when I return a reference parameter passed to a function?

Let's say I have the following function: 假设我有以下功能:

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

First question, does the return statement copy the value of the reference x since the function is not returning an int&. 第一个问题,return语句是否复制了引用x的值,因为函数没有返回int&。

Second question, why can't I call the function with a literal? 第二个问题,为什么我不能用文字调用函数? What if I did want to call the function sometimes with a literal sometimes with a value? 如果我确实想要使用有时带有值的文字调用函数怎么办? I tried overloading with 我尝试过载

int f(int x)
{
  x++;
  return x;
}

It compiles if I call with literal. 如果我用文字调用它会编译。 But when I pass a variable I get ambiguous call error. 但是当我传递一个变量时,我得到了模糊的调用错误。 Is there a way to accomplish this? 有没有办法实现这个目标?

Maybe this is what you want: 也许这就是你想要的:

int F(const int& x) { return x + 1; }
int F(int& x) { x++; return x; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当您从 c++ function 返回引用时会发生什么? - What happens when you return a reference from a c++ function? 如果将 function 返回值传递给 function 引用参数,那么 C++ 会发生什么? - What happens in C++ if a function return value is passed to a function reference argument? 如果参数被传递两次,会发生什么情况? 一次按值,一次按引用? 会修改还是不修改? - What happens to a parameter if it is passed twice? Once by value and once by reference? Will it be modified or not? 当我在C ++中存储指向按值传递参数的指针时会发生什么? - What happens when I store a pointer to a parameter passed-by-value in C++? 将传递引用变量分配给struct成员时会发生什么 - What happens when assigning passed-by-reference variable to struct member 如果我得到了一个与符号一起传递的变量的引用,将会发生什么? - What happens if I get the reference of a variable passed with an ampersand? 当我们进行向下转换时,内部会发生什么? - What happens internally when we do downcasting? 调用 std::move 时内部会发生什么? - What happens internally when std::move is called? 当一个指针作为指向另一个函数内部的指针的指针传递时会发生什么? - what happens when a pointer is passed as a pointer to a pointer inside another function? 将值传递给 C++ 中的运算符重载器 function 时会发生什么? - What happens when value is passed to operator overloader function in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM