功能结果不能作为参考传递

Dan*_*sky 5 c++ reference

经过多年的AS3,我正在尝试重新学习C++.参考资料仍然适合我.

考虑以下功能:

#include <cstdio>
#include <list>

void f(std::list<int>& v) {
  for (std::list<int>::iterator i = v.begin(); i != v.end(); ++i)
    printf("Hello %d\n", *i);
}

std::list<int> get(void) {
  std::list<int> list;
  list.push_back(0);
  return list;
}
Run Code Online (Sandbox Code Playgroud)

现在,执行以下操作:

std::list<int> l = get();
f(l);
Run Code Online (Sandbox Code Playgroud)

很好,但f(get())会产生以下错误:

"没有用于调用'f'的匹配函数","候选函数不可行:没有已知的从''std :: list <int>'转换为'std :: list <int>&'作为第一个参数"

这是为什么?是因为函数的结果是不可见的const吗?

jua*_*nza 8

当你这样做:

f(get());
Run Code Online (Sandbox Code Playgroud)

你临时传递std::list<int>f().临时无法绑定到非const引用.因此,您可以通过传递const引用来解决此问题,因为您不想修改参数.

void f(const std::list<int>& v) 
{ //   ^^^^^
  for (std::list<int>::const_iterator i = v.begin(); i != v.end(); ++i)
  { //                 ^^^^^^^^^^^^^^
    printf("Hello %d\n", *i);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意,这需要你使用a const_iterator,因为std::list::begin() const和相应的end()方法返回const_iterators.在C++ 11中,您可以将其简化为

for (auto i = v.begin(); i != v.end(); ++i)
  ...
Run Code Online (Sandbox Code Playgroud)

甚至

for (const auto& i : v)
  std::cout << i << "\n";
Run Code Online (Sandbox Code Playgroud)