如何通过“字面的”整数在C ++中的引用(Newbie) [英] How to pass "literal" integers by reference in C++ (Newbie)

查看:84
本文介绍了如何通过“字面的”整数在C ++中的引用(Newbie)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:正如许多人已经指出的,pass-by-reference通常不适合作为原始类型的优化。这是很好的知道,所以谢谢大家!即使如此,我的问题更多的是为什么字面值不能通过参考传递,这已被接受的答案解决。干杯!



(原谅我的天真:我对C ++很新鲜。)



在调用函数(例如,fillRect)时,通过按值复制,我想通过引用传递参数。



如果我提供参数声明local变量,它工作正常。但是如果我提供任何作为字面的整数,我得到一个编译错误(没有匹配的函数)。

  void fillRect & x,int& y,int& width,int& height)
{
// do something
}

int x = y = 20,w = 100,h = 80;

fillRect(x,y,w,h); //这个编译和工作!
fillRect(x,y,100,80); //但这不编译...为什么?

有什么作用?

解决方案

您不能将文字绑定到非const引用的值(因为修改文字的值不是有意义的操作)。



因此,如果您将 fillRect 声明为:

  void fillRect(int const& x,int const& y,int const& width,int const& height)

在这种情况下,您将传递 int

>函数 fillRect 可能是如此昂贵,以致传递其参数的成本在任何情况下都是完全不相关的。或者也许它将是内联的,并且没有任何成本通过论据。这些微优化通常不是优化,并且应始终由分析结果(如果它们完成的话)指导。


EDIT: As many people have pointed out, pass-by-reference isn't generally appropriate as an optimisation for primitive types. This is excellent to know, so thank you all! Even so, my question was really more about why literal values can't seem be passed by reference, which has been addressed by the accepted answer. Cheers!

(Forgive my naivety: I'm pretty new to C++.)

To avoid the inefficiency of copy-by-value when calling a function (say, "fillRect"), I want to pass the parameters by reference.

If I supply the parameters as declared local variables, it works fine. But if I supply any as "literal" integers, I get a compile error (no matching function).

void fillRect( int &x, int &y, int &width, int &height )
{
    // do something
}

int x=10, y=20, w=100, h=80;

fillRect(x, y, w, h); // this compiles and works!
fillRect(x, y, 100, 80); // but this doesn't compile ... why?

What gives?

解决方案

You cannot bind a literal to an lvalue reference to non-const (because modifying the value of a literal is not an operation that makes sense). You can however bind a literal to a reference to const.

So this will compile if you declare fillRect as:

void fillRect(int const& x, int const& y, int const& width, int const& height)

In this case you are passing ints. ints are so cheap to copy that passing by them by reference will probably make the performance of your program worse.

The function fillRect is probably so expensive that the cost of passing its arguments is totally irrelevant in any case. Or maybe it will be inlined, and there will be no cost whatsoever to passing the arguments. These sorts of micro-optimisations are usually not optimisations at all, and should always be guided by the results of profiling (if they are done at all).

这篇关于如何通过“字面的”整数在C ++中的引用(Newbie)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆