提升变量在1_54中被破坏?

时间:2013-11-01 00:03:11

标签: c++ boost c++11 variant

我认为Boost :: variant在1_54中被破坏。 我试图在boost变体中使用std :: unique_ptr作为有界类型。

根据1_54文档,变体需要是可复制的或Move Constructable。

http://www.boost.org/doc/libs/1_54_0/doc/html/variant/reference.html

所以我实现了移动构造函数并在我的代码中禁用了复制构造函数。

当我尝试将某些内容分配给变体对象时,它无法编译。 我尝试了各种不同的东西,包括使用std :: move为变量对象分配数据,但似乎没有任何效果。 在编译错误堆栈跟踪之后我确定问题出在variant.hpp中,它试图备份rhs数据。我想知道你们的想法,如果我认为提升变体文档是错误的,请告诉我。

提前致谢。

我正在使用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;
}

1 个答案:

答案 0 :(得分:4)

  

我的代码是否为任何人编译?

不,它不会,变体将尝试调用缺少的复制构造函数。 (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::vectorvariant将拒绝移动东西,因为它不会是异常安全的。

    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();
}
相关问题