[英]boost::variant: strange behaviour with a recursive vector type
我有一个成员是一类boost::variant
两类:一vector
整数和vector
包含类对象(后者显然需要的帮助下完成的recursive_wrapper
)。 该类的代码如下
#include <boost/variant/variant.hpp>
#include <boost/variant/recursive_wrapper.hpp>
#include <vector>
class TestVariant
{
public:
typedef boost::variant< std::vector<int>, boost::recursive_wrapper<std::vector<TestVariant> > > StorageType;
TestVariant():
m_value{ std::vector<int>{} }
{}
TestVariant(const TestVariant& other):
m_value{ other.m_value }
{}
TestVariant& operator=(const TestVariant& other)
{
m_value = other.m_value;
return *this;
}
TestVariant(TestVariant&& other):
m_value{ std::move(other.m_value) }
{}
TestVariant& operator=(TestVariant&& other)
{
m_value = std::move(other.m_value);
return *this;
}
TestVariant(const std::vector<int>& value):
m_value{ value }
{}
TestVariant(std::vector<int>&& value):
m_value{ std::move(value) }
{}
TestVariant(const std::vector<TestVariant>& value):
m_value{ value }
{}
TestVariant(std::vector<TestVariant>&& value):
m_value{ std::move(value) }
{}
private:
StorageType m_value;
};
当我尝试通过创建TestVariant
的vector
并包含TestVariant的递归实例的实例来使用此类时,如下所示
std::vector<TestVariant> v;
v.emplace_back(std::vector<TestVariant>{ std::vector<TestVariant>{}, std::vector<int>{} }); // access violation!
我在MSVS 2013和Boost ver 1.53下收到“访问冲突”异常(我知道这是Boost的旧版本,但目前在组织上我只能使用它)。 大肠杆菌上的相同代码可以正常工作(请参阅此处 )。
更奇怪的是,如果我切换两个向量的顺序,MSVS 2013中的一切似乎都很好
std::vector<TestVariant> v;
v.emplace_back(std::vector<TestVariant>{std::vector<int>{}, std::vector<TestVariant>{} }); // works!
有任何想法吗? 我已经尝试解决这一问题了一天...
实际上,这似乎是具有统一的初始化/初始化列表的许多错误之一。 代码是“精细的”(在某种意义上说不会触发UB)
如果与我遇到的错误类似,则可以尝试明确指定类型名称:
v.emplace_back(std::vector<TestVariant>{
TestVariant(std::vector<TestVariant>{}),
TestVariant(std::vector<int>{}) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.