为什么要将对象的副本作为函数的参数?为什么 const ref 不是参数的默认方式? [英] Why would you ever take the copy of an object as a parameter to your function? Why are not const ref the default way of parameters?

查看:49
本文介绍了为什么要将对象的副本作为函数的参数?为什么 const ref 不是参数的默认方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我很喜欢 C++ 编程,但有一件事我真的不明白.对我来说,最常见的函数编程方式似乎是这样的:

As much as I enjoy C++ programming, there is one thing I really don't get. To me, it seems that the most common way of programming a function is like this:

some_function(a variable)
    do something according to the data in the variable

示例:

bool match_name(const std::string& name)
{
    return this->name == name;
}

我发现自己对代码中 90% 的函数参数使用了 const ref(也许我做错了什么).

I find myself using const ref for 90% of all function parameters in my code (maybe I'm doing something wrong).

我的问题是:为什么变量的副本是默认"类型的参数?为什么 const ref 不是默认值?

My question is: Why is a copy of the variable the "default" type of parameters? Why are not const ref the default?

为什么不是这样的?:

void my_function(My_type object)      // <- const ref

void my_function(ref My_type object)  // <- ref (mutable)

void my_function(copy My_type object) // <- copy

推荐答案

C++ 希望与 C 兼容,并且由于 C 默认使用值语义,因此 C++ 也是如此.按值获取内置类型而按引用获取其他类型会非常不一致.

C++ wants to be compatible with C, and since C uses value semantics by default, so does C++. It would be very inconsistent to take build-in types by value but other types by reference.

然而,通过引用传递并不总是更好.引用导致的指针间接通常会使编译器更难优化代码生成.在很多情况下,通过值传递类型仍然比通过引用传递更好.这取决于类型.引用的指针间接可能导致内存读取,而按值传递允许对象在 CPU 寄存器中传递.例如,这样的类型:

However, passing by reference is not always better. The pointer indirection a reference causes generally makes it harder for the compiler to optimize code gen. In many cases, passing a type by value is still better than by ref. It depends on the type. The pointer indirection of references might cause a memory read, while passing by value allows the object to be passed in CPU registers. For example, a type like this:

class Point {
public:
    /* functions */
private:
    int x;
    int y;
};

应该总是按值传递.它只是两个整数.引用可能会导致不需要的内存读取来获取值.

Should always be passed by value. It's just two integers. A reference might cause unneeded memory reads to get to the values.

此外,有时即使类型无法注册,您也希望按值传递.例如,由于移动语义,需要存储传递的值的所谓接收器函数"对值的性能更好.主要示例是构造函数和设置函数:

Also, sometimes you want to pass by value even if the type cannot be enregistered. So called "sink functions" for example that need to store the passed value perform better with values due to move semantics. Prime examples are constructros and setters:

void SomeClass::setString(std::string s)
{
    this->s_ = std::move(s);
}

在这种情况下通过引用传递可能会产生额外的副本.您可以在线阅读更多相关信息.一个很好的起点是这个 SO 问题:

Passing by reference in this case can incur extra copies. You can read up more on this online. A good starting point is this SO question:

是通过const std的日子::字符串&作为参数结束?

这篇关于为什么要将对象的副本作为函数的参数?为什么 const ref 不是参数的默认方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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