简体   繁体   English

在 C++ 中输出参数与返回值

[英]In C++ Output Parameter vs Return Value

What is/are the difference(s) between output parameters and return values?输出参数和返回值之间的区别是什么? I've looked everywhere and I can't seem to find a simple definition for either.我到处找,似乎都找不到一个简单的定义。

  • The return value is something well defined in C++;返回值是在 C++ 中很好定义的东西; for instance, x in return x;例如, x return x; is the return value, whereas int in the function declaration int myfunc() is the return type.是返回值,而int在函数声明int myfunc()是返回类型。
  • The concpet of output paramters is not defined in C++.输出参数的概念在 C++ 中没有定义。 However someone would interpret it as either of the following:然而,有人会将其解释为以下任一情况:
    • function parameters passed by non- const reference, as long as you actually modify it in the function , otherwise why would you call it output ?const引用传递的函数参数,只要你实际在函数中修改它,否则为什么会称它为output An example is x in the following function declaration: void myfunc(int& x) ;下面的函数声明中的x就是一个例子: void myfunc(int& x) ;
    • function parameters passed by (not necessarily const ) pointer to non- const , like x in both the following function declarations: void fun1(int * x) and void fun2(int * const x) ;函数参数通过(不一定是const )指向非const指针传递,就像下面两个函数声明中的x一样: void fun1(int * x)void fun2(int * const x)
      • concerning this latter case, it allows "encoding" a missing parameter in as a nullptr default value, as in void fun3(int * x = nullptr) .关于后一种情况,它允许将缺失的参数“编码”为nullptr默认值,如void fun3(int * x = nullptr)

A first difference is aesthetic: which one you like the most?第一个区别是审美:你最喜欢哪个?

Another one is that the former concept and syntax help you convey the message that the function is giving back a value, something which is clear at the call site too (whereas at the call site you might not know if a parameter corresponding to an argument is passed by reference or not).另一个是前一个概念和语法可以帮助您传达函数正在返回值的消息,这在调用站点也很清楚(而在调用站点,您可能不知道与参数对应的参数是否为是否通过引用传递)。

There are several differences between this two ways a function can have "consequences" at the caller site.函数在调用者站点上产生“后果”的这两种方式之间存在一些差异 For instance, you can only have one return value, whereas you can have as many paramters as you like.例如,您只能有一个返回值,而您可以拥有任意数量的参数。

Performancewise, complier optimizations can minimize the difference in performance, and maybe you should not worry (yet) about it.性能方面,编译器优化可以最大限度地减少性能差异,也许您(还)不应该担心它。

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

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