在c++中,是通过值传递更好,还是通过引用到const传递更好?

我不知道哪种做法更好。我意识到,通过引用传递到const应该在程序中提供更好的性能,因为您没有对变量进行复制。


当前回答

听起来你得到答案了。传递值是昂贵的,但是如果需要的话,可以给您提供一个副本。

其他回答

根据经验,value用于非类类型,const引用用于类。 如果一个类非常小,最好是通过值传递,但区别很小。你真正想要避免的是按值传递一些巨大的类,并将其全部复制——如果你传递的是一个std::vector,其中包含相当多的元素,这将产生巨大的差异。

这取决于类型。这样就增加了必须进行引用和取消引用的小开销。对于大小等于或小于使用默认复制ctor的指针的类型,按值传递可能会更快。

听起来你得到答案了。传递值是昂贵的,但是如果需要的话,可以给您提供一个副本。

正如已经指出的,这取决于类型。对于内置数据类型,最好按值传递。即使是一些非常小的结构,比如一对int型,通过传递值也可以执行得更好。

这里有一个例子,假设你有一个整数值,你想把它传递给另一个例程。如果该值已优化为存储在寄存器中,那么如果要将其传递为引用,则必须首先将其存储在内存中,然后将指向该内存的指针放置在堆栈中以执行调用。如果是按值传递,所需要的只是将寄存器推入堆栈。(与给定不同的调用系统和cpu相比,细节要复杂一些)。

如果你在做模板编程,你通常被迫总是通过const ref传递,因为你不知道传递的类型。通过值传递错误值的惩罚要比通过const ref传递内置类型的惩罚严重得多。

这是我在设计非模板函数的接口时通常采用的方法:

Pass by value if the function does not want to modify the parameter and the value is cheap to copy (int, double, float, char, bool, etc... Notice that std::string, std::vector, and the rest of the containers in the standard library are NOT) Pass by const pointer if the value is expensive to copy and the function does not want to modify the value pointed to and NULL is a value that the function handles. Pass by non-const pointer if the value is expensive to copy and the function wants to modify the value pointed to and NULL is a value that the function handles. Pass by const reference when the value is expensive to copy and the function does not want to modify the value referred to and NULL would not be a valid value if a pointer was used instead. Pass by non-const reference when the value is expensive to copy and the function wants to modify the value referred to and NULL would not be a valid value if a pointer was used instead.