我认为 Boost::variant 在 1_54 中被破坏了。 我正在尝试将 std::unique_ptr 用作 boost 变体中的有界类型。
根据 1_54 文档,变体需要可复制构造或可移动构造。
http://www.boost.org/doc/libs/1_54_0/doc/html/variant/reference.html
所以我在我的代码中实现了移动构造函数并禁用了复制构造函数。
当我尝试将某些内容分配给变体对象时,它无法编译。 我尝试了各种不同的方法,包括使用 std::move 将数据分配给变体对象,但似乎没有任何效果。 根据编译错误堆栈跟踪,我确定问题出在 variant.hpp 中,它试图备份 rhs 数据。我想知道你们的想法,如果我认为 boost 变体文档是错误的,请告诉我。
提前致谢。
我正在使用 vs2010 和 C++11 进行编译。
这是我的测试代码:
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
#include <string>
#pragma warning (push)
#pragma warning (disable: 4127 4244 4265 4503 4512 4640 6011)
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <boost/ref.hpp>
#include <boost/shared_ptr.hpp>
#pragma warning (pop)
#include <boost/foreach.hpp>
#include <boost/format.hpp>
using boost::format;
using boost::str;
using namespace std;
class UniqueTest
{
};
class Foo
{
public:
std::unique_ptr<UniqueTest> testUniquePtr;
Foo() { std::cout << "Foo::Foo\n"; }
Foo (Foo&& moveData)
{
}
Foo& operator=(Foo&& moveData)
{
return *this;
}
private:
Foo(Foo& tt);
Foo& operator=(const Foo& tt);
};
int main()
{
Foo x = Foo();
boost::variant<std::wstring,Foo> m_result2;
std::wstring testString = L"asdf";
m_result2 = testString; //Fails
//m_result2 = std::move(testString); //Fails
//m_result2 = std::move(x); //Fails
boost::get<Foo>(m_result2).testUniquePtr.get ();
return 0;
}
最佳答案
Does my code as is compile for anyone?
不,它不会,变体将尝试调用缺少的复制构造函数。 (Foo::Foo(Foo const&)
甚至没有声明):
boost/variant/variant.hpp|756 col 9| error: no matching function for call to ‘Foo::Foo(const Foo&)’
即使您确实声明了它,它也不会起作用:
test.cpp|43 col 6| error: ‘Foo::Foo(const Foo&)’ is private
评论里有提到但是你需要
使复制构造函数成为复制构造函数(为了好的风格)
Foo(Foo const& tt) = delete; Foo& operator=(const Foo& tt) = delete;
使移动构造函数/赋值
noexcept
,否则(如std::vector
)variant
将拒绝移动东西因为它不会异常安全。Foo(Foo && moveData) noexcept { } Foo& operator=(Foo && moveData) noexcept { return *this; }
这是一个在 GCC 和 Clang 上编译的简化示例:
#include <iostream>
#include <memory>
#include <string>
#include <boost/variant.hpp>
struct UniqueTest { };
struct Foo
{
public:
std::unique_ptr<UniqueTest> testUniquePtr;
Foo() { std::cout << "Foo::Foo\n"; }
Foo(Foo && moveData) noexcept { }
Foo& operator=(Foo && moveData) noexcept { return *this; }
Foo(Foo const& tt) = delete;
Foo& operator=(const Foo& tt) = delete;
};
int main()
{
Foo x = Foo();
boost::variant<std::wstring, Foo> m_result2;
std::wstring testString = L"asdf";
m_result2 = testString; //Fails
//m_result2 = std::move(testString); //Fails
//m_result2 = std::move(x); //Fails
boost::get<Foo>(m_result2).testUniquePtr.get();
}
关于c++ - 在 1_54 中破坏了 boost 变体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19718726/