Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.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++ boost变体复制语义_C++_Boost_Boost Variant - Fatal编程技术网

C++ boost变体复制语义

C++ boost变体复制语义,c++,boost,boost-variant,C++,Boost,Boost Variant,我想知道boost变体的复制语义是什么。我已经检查了源代码,这让我有点困惑,所以在示例代码中,我想知道我的getVal(name)函数在返回时是否复制了基础向量?如果是,我是否应该将其改为返回的引用(&) using Val = boost::variant<std::vector<int>, std::vector<std::string>>; Val getVal(std::string& name) { return map[name];//

我想知道boost变体的复制语义是什么。我已经检查了源代码,这让我有点困惑,所以在示例代码中,我想知道我的
getVal(name)
函数在返回时是否复制了基础向量?如果是,我是否应该将其改为返回的引用(&)

using Val = boost::variant<std::vector<int>, std::vector<std::string>>;

Val getVal(std::string& name) {
 return map[name];// where map is std::map<std::string, Val>
}
使用Val=boost::variant;
Val getVal(标准::字符串和名称){
返回map[name];//其中map是std::map
}

是,您的
getVal
返回整个向量的副本(包括所有元素字符串的副本,例如)

是的,返回一个引用可以解决这个问题


注意您还可以拥有一个存储引用的变体。在这种情况下,通过“value”返回它仍然与返回引用具有相同的语义:

using Ref = variant<std::vector<int>&, std::vector<std::string>&>;

Ref getVal(std::string& name) {
   return map[name]; // where map is std::map<std::string, Val>
}
输出:

1 2 3 4 five six seven eight 

在没有复制任何向量的情况下

如果更改它,它可能应该是一个常量引用。
1 2 3 4 five six seven eight