我应该发送std::set函数与参考或不
Should I send std::set to function with refrence or not?
从另一个问题中我看到了以下代码:
template <typename T>
std::set<T> getUnion(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result = a;
result.insert(b.begin(), b.end());
return result;
}
我们就不能用下面的代码吗?:
template <typename T>
std::set<T> getUnion(std::set<T> a, const std::set<T>& b)
{
a.insert(b.begin(), b.end());
return a;
}
有什么区别吗??
我不明白为什么用第一种方法。
第二个代码是否抑制RVO ?
第一个版本通过引用获取std::set
,这意味着您将不会获得传递的参数的副本。复制实际上发生在result
和a
的初始化过程中。第二个方法按值接受实参,这意味着编译器将根据实参的值类别调用复制/移动构造函数。特别是,如果参数是左值,则复制它,如果是右值,则移动它。
在第一个例子中,编译器很可能会放弃返回语句中的复制操作,这种优化称为返回值优化(RVO)。第二个版本不能这样做,因为您没有返回一个局部变量。因此,您可以看到,函数的第二个版本必须引起至少一个额外的复制或移动操作,而第一个版本只处理一个操作。
实际上这两个函数是等价的。在调用函数
时,通过复制对应于形参a的实参创建一个新的集合。template <typename T>
std::set<T> getUnion(std::set<T> a, const std::set<T>& b)
{
//...
或者在
函数体中创建template <typename T>
std::set<T> getUnion(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result = a;
//...
然而,当函数定义为在第一种情况下
时,对于代码的读者来说更清楚template <typename T>
std::set<T> getUnion(const std::set<T>& a, const std::set<T>& b);
例如,函数可以声明为
template <typename T>
std::set<T> getUnion( const std::set<T> &a, std::set<T> b);
可以吗?
这些变化只会引起问题。
相关文章:
- 通过参考变差函数传递N-D数组
- 函数参数绑定通过参考与传递指针传递数组的规则
- 如何调用成员初始化器列表中参考成员的构造函数
- 函数采用原始指针试图通过错误msg中概述的参考来接受指针
- 为什么即使传递给函数作为参考,指针也未被分配
- 为什么通用参考概念不适用于函数指针的地图插入
- 使用Arduino IDE的构造函数的未定义参考错误
- 未定义的参考错误链接天然函数Android
- 如何将rvalue作为参考参数传递给函数
- 超载函数既不按值,也不是通过参考来对象,而是将撤销的指针换成对象
- 为什么该函数不会获得动态数组?(我正在使用指针和参考)
- 无法将类对象转换为函数默认参数中的参考
- 当通过函数中的参考调用时,标识符不确定
- 是否有一种方法可以始终通过值(制作副本)而不是在使用类成员函数时通过参考来传递
- std ::函数方法参考无法将dword投入到dword64
- rvalue参考vector :: push_back函数如何提高效率
- 函数返回rvalue参考是否有意义
- Python ctypes,回调函数增强类型是C++参考
- 在 GetProcAddress 的 lpProcName 中是否有 DLL 函数修饰的参考
- C++ 使用无法更改的通用参考函数模板实现过载分辨率