简体   繁体   English

按值返回常数和非常数

[英]Return constant and non constant by value

There is such code: 有这样的代码:

   const int fun(){ return 2; } // can be assigned to int and const int
   int fun2(){ return 2; } // can be assigned to int and const int

Is there any difference in using these functions? 使用这些功能有什么区别吗? They both return by value so it is always copied at the end of function call. 它们都按值返回,因此总是在函数调用结束时将其复制。

Is there any difference in using these functions? 使用这些功能有什么区别吗?

No. There is, however, a difference in their type , and if the functions returned a class type, there would be difference regarding invoking methods on the return value . 否。但是, 它们的类型有所不同 ,如果函数返回的是类类型,则在返回值上调用方法的方法也会有所不同

There's no practical difference when returning an int , basically because anything you do with a temporary of builtin type only needs its value. 返回int并没有实际的区别,基本上是因为您对内置类型的临时类所做的任何事情都只需要其值即可。 You can take a const reference to a temporary - it may be valid (if unwise) in the latter case to cast that const reference to non-const and modify the temporary through it, but I can't be bothered to look up whether temporaries of builtin type really are mutable, and there's not any great practical need to do anything like that. 您可以使用const引用临时文件-在后一种情况下,将const引用转换为非const并通过它修改临时文件可能是有效的(如果不明智的话),但是我不费心查找临时文件是否为临时文件内置类型确实是可变的,并且没有任何实际需要进行此类操作。

When returning a class type there is a difference - in the second case you can call a non-const member function on the function's return value, and in the first case you can't. 返回类类型时存在区别-在第二种情况下,您可以在函数的返回值上调用非const成员函数,而在第一种情况下,则不能。 For example, given std::string fun2() { return "hello"; } 例如,给定std::string fun2() { return "hello"; } std::string fun2() { return "hello"; } you can do std::cout << (fun2() += " world\\n"); std::string fun2() { return "hello"; }您可以执行std::cout << (fun2() += " world\\n"); , or std::string s("foo"); std::cout << s; fun2().swap(s); std::cout << "s"; std::string s("foo"); std::cout << s; fun2().swap(s); std::cout << "s"; std::string s("foo"); std::cout << s; fun2().swap(s); std::cout << "s"; . Such tricks are potential optimizations (especially before C++11 move semantics came along), and they don't work if fun2 returns const std::string . 这样的技巧是潜在的优化(特别是在C ++ 11移动语义出现之前),如果fun2返回const std::string则这些技巧不起作用。 The second trick is called "swaptimization", which at least tells you that it's used enough to be worth naming. 第二个技巧称为“ swaptimization”,它至少告诉您它已足够使用以值得命名。

There is no difference in using these functions. 使用这些功能没有区别。 Note that your assumption that copying would happen may not be true in the face of an optimizer, that would probably inline the value 2 at the call site. 请注意,面对优化器,您可能会进行复制的假设可能并不正确,这可能会使调用站点的值2内联。

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

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