将参数传递给函数而不将其包装到std :: ref中,而将参数指定为const引用

我有以下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);
}

So here parameter of the function get_first is const reference,

while I pass whole vector some_vec instead of wrapping it into std::ref. Does c++ copies full object here?

评论
  • 小辣条
    小辣条 回复

    std::ref is not for that. It is used to convert an existing reference to an object, used where a reference cannot be accepted, like within a std::vector<>. The idea is that references cannot be reassigned or set to null, so stuff in STL containers like moving etc wouldn't work with a raw reference. Most likely it internally converts the wrapped reference into a pointer.

    在您的示例中,参数自动作为参考传递。