Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用C+中的自定义类型通过常量引用传递向量+;_C++_Pass By Reference - Fatal编程技术网

C++ 用C+中的自定义类型通过常量引用传递向量+;

C++ 用C+中的自定义类型通过常量引用传递向量+;,c++,pass-by-reference,C++,Pass By Reference,假设您有自定义类型 class Foo {} 是通过const引用将Foo类型的向量传递给这样的方法的正确方法 void f(const std::vector<const Foo&>& bar); void f(const std::vector&bar); 或者我应该这样做 void f(const std::vector<Foo>& bar); void f(const std::vector&bar); 我更想知道我更喜欢使用哪一

假设您有自定义类型

class Foo {}
是通过const引用将Foo类型的向量传递给这样的方法的正确方法

void f(const std::vector<const Foo&>& bar);
void f(const std::vector&bar);
或者我应该这样做

void f(const std::vector<Foo>& bar);
void f(const std::vector&bar);

我更想知道我更喜欢使用哪一种类型。

您应该将
const std::vector&
作为类型传递。这可以防止在调用函数时获取向量的值副本

请注意,当前标准不允许使用
std::vector
:std::vector不能包含引用类型。

您可以尝试。(通过调用
f
其他地方)“seam都可以编译和工作。”演示。我一秒钟也不相信任何代码可以在函数签名中交换
vector
vector
,并且仍然为同一调用站点编译。。。因为容器不能包含引用,所以后者无论如何都不是有效的。