将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
Pass object to a function without wrapping it into std::ref, while argument is specified as a const reference
我有以下c ++代码(只是一个问题的简单示例(
#include <iostream>
#include <string>
#include <vector>
double get_first(const std::vector<double>& vec) {
return vec[0];
}
int main()
{
std::vector<double> some_vec = {1, 2};
std::cout << get_first(some_vec);
}
所以这里的函数get_first
参数是常量引用,
当我传递整个向量some_vec
而不是将其包装到 std::ref 中时。c++ 会在此处复制完整对象吗?
std::ref
不是为了这个。它用于将现有引用转换为对象,用于无法接受引用的情况,例如在std::vector<>
中。这个想法是引用不能重新分配或设置为 null,因此 STL 容器中的内容(如移动等(不适用于原始引用。很可能它在内部将包装的引用转换为指针。
在您的示例中,参数会自动作为引用传递。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用