提升变体复制语义
boost variant copy semantics
我想知道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>
}
是的,您的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>
}
具有从Ref
转换为Val
的必要机制的完整示例(反之亦然):
住在科里鲁
#include <boost/variant.hpp>
#include <map>
#include <vector>
#include <string>
using Val = boost::variant<std::vector<int>, std::vector<std::string>>;
using Ref = boost::variant<std::vector<int>&, std::vector<std::string>& >;
std::map<std::string, Val> map {
{ "first", std::vector<int> { 1,2,3,4 } },
{ "2nd", std::vector<std::string> { "five", "six", "seven", "eight" } }
};
namespace { // detail
template <typename T>
struct implicit_convert : boost::static_visitor<T> {
template <typename U> T operator()(U&& u) const { return std::forward<U>(u); }
};
}
Ref getVal(std::string& name) {
return boost::apply_visitor(implicit_convert<Ref>(), map[name]);
}
#include <iostream>
int main() {
for (auto i : boost::get<std::vector<int> >(map["first"])) std::cout << i << " ";
for (auto i : boost::get<std::vector<std::string> >(map["2nd"])) std::cout << i << " ";
}
输出:
1 2 3 4 five six seven eight
无需复制任何向量
相关文章:
- 使用移动和复制语义时函数匹配如何工作?
- 移动语义和深层/浅层复制之间有什么关系?
- 了解构造函数在移动、复制、赋值语义中的行为
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 复制省略并在返回值中移动语义
- 在一个微不足道的可复制结构中,移动语义应该实现吗?
- 在'string=string+s1'和"string+=s1"之间移动语义可以保存多少个复制操作?
- C++复制构造函数和移动语义之间的区别
- 默认情况下,返回是否使用移动或复制语义
- 我应该依赖复制省略还是移动语义
- 在封装指针的类中,移动语义无意中被复制构造函数取代
- 为什么 boost::make_shared 使用复制语义
- 复制有状态分配器:标准库分配器语义和内部内存
- 每次复制实现移动分配的非 const 对象时,我是否总是获得移动语义
- 复制语义和比较
- 提升变体复制语义
- 有没有办法使用 move 而不是复制语义将函数返回值(对象)包装在 Python 中
- 消除默认/删除移动/复制语义中涉及的样板的好方法是什么
- 绕过c++中的复制语义
- std::数组复制语义