根据cppreference,变量不允许分配动态内存。这表明变体不应该像向量和映射一样,将动态分配的容器作为模板。然而,有人说,有可能有一个载体作为变体模板。可能是变体存储了向量指针或引用,而不是实际结构本身吗?
我想要一个存储向量和地图的变体。我想到了两种可能性:
std::variant<std::vector<int>, std::map<int, int> > x; //stores within the variant itself ??
std::variant <std::uniqur_ptr<std::vector<int> >, std::unique_ptr<std::map<int, int> > > y; //stores only a pointer. The container is allocated elsewhere.
我更喜欢第一种选择,因为它很简单。让我知道你的想法!
根据cppreference,变量不允许分配动态内存。
你误解了这意味着什么。std::variant
不允许通过动态分配包含的对象来实现,但允许该包含的对象做它通常做的任何事情。
这是之间的区别
class incorrect_variant {
union {
std::vector<int> * vector;
std::map<int, int> * map;
} u;
enum kind {
is_vec,
is_map,
} k;
public:
incorrect_variant(std::vector<int> value) : u(new std::vector<int>(value)), k(is_vec) {}
// etc
}
class correct_variant {
std::aligned_storage<std::max(sizeof(std::vector<int>), sizeof(std::map<int, int>)> storage;
enum kind {
is_vec,
is_map,
} k;
public:
correct_variant(std::vector<int> value) : k(is_vec)
{
new (storage) std::vector<int>(value);
}
// etc
}
std::vector<T>
是一个带有指针的类,用于管理动态分配的内存。
CCD_ 3通过不";被允许分配存储器";不能将std::vector<T>
对象本身存储在动态内存中,但向量可以管理自己的动态内存。
你搞错了。
variant
类本身不分配一个字节(否则它可能会有一个分配器模板参数(。所有的东西都是本地的。但是;可变的";类型本身可以随心所欲地分配内存。他们拥有自己的记忆,而这些都与std::variant
无关。不是有点像std::string
s的数组吗?当然,C数组本身不会分配任何东西,但单个元素(字符串(必须进行一些分配。