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

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


当前回答

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

其他回答

为小类型传递值。

但是,在c++ 11中,如果您要使用数据,则通过值传递,因为您可以利用move语义。例如:

class Person {
 public:
  Person(std::string name) : name_(std::move(name)) {}
 private:
  std::string name_;
};

现在调用代码会做:

Person p(std::string("Albert"));

并且只会创建一个对象,并直接移动到类Person中的成员name_中。如果传递const引用,则必须创建一个副本以将其放入name_中。

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

简单的区别:-在函数中,我们有输入和输出参数,所以如果你传递的输入和输出参数相同,那么使用引用调用,否则,如果输入和输出参数不同,那么最好使用值调用。

示例无效金额(int账户,int存款,int总数)

输入参数:账户、存款 输出参数:total

输入和输出是不同的使用值调用

无效金额(int total, int deposit)

投入总保证金 输出总

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

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.

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