【问题标题】:boost::containers and error: "C2679: binary '=': no operator found"boost::containers 和错误:“C2679:二进制 '=':找不到运算符”
【发布时间】:2012-12-25 03:12:01
【问题描述】:

我正在尝试在 Visual Studio 2008 下编译以下代码:

struct test
{
    boost::container::vector<int> v1;
};
test v1, v3;
const test & v2 = v3;
v1 = v2;

我得到的错误是:
error C2679: binary '=' : no operator found which take a right-hand operand of type 'const test'(或者没有可接受的转换) 可能是“测试 &test::operator =(test &)” 在尝试匹配参数列表'(test, const test)'时

当使用普通的 std::vector 而不是 boost::container 等效项时,代码会编译。我正在寻找为什么此代码无法编译以及如何使其编译的答案。

【问题讨论】:

  • FWIW,以下代码在 MSVC10 下编译:#include struct test { boost::container::vector v1; }; int main() { 测试 v1, v3;常量测试 & v2 = v3; v1 = v2; }
  • 另一个 FWIW:使用 -std=gnu++03 的 GCC 4.7.2 以类似于 VC++ 2008 的方式失败。它使用 -std=gnu++11 编译得很好,但话又说回来,boost move 库的全部要点(其中是 boost::container::vector 正在使用的导致问题的)是为 C++03 实现提供移动语义,因此使用支持 C++11 移动语义的编译器/编译器模式编译时没有问题也就不足为奇了。看起来在处理可复制的 const 对象的 boost move 中可能存在错误。

标签: visual-studio-2008 visual-c++ boost


【解决方案1】:

我发现了一个已经被问过的类似问题: boost::container::vector fails to compile with C++03 compiler

我们观察到的行为似乎是为 boost 社区设计和知晓的: Boost::move emulation limitations 章节“派生自或持有可复制和可移动类型的类中的赋值运算符”。

为了使主要问题中显示的代码能够工作,必须使用 BOOST_COPYABLE_AND_MOVABLE 宏将类声明为可复制和可移动的。复制分配的 const 版本也需要明确定义。 C++03编译器的代码修正版本:

class test
{
private:
    BOOST_COPYABLE_AND_MOVABLE( test );
public:
    test& operator=(BOOST_COPY_ASSIGN_REF(test) p) // Copy assignment
    {
        v1 = p.v1;
        return *this;
    }
    boost::container::vector<int> v1;
};

那些额外的类装饰确实会变得很烦人,尤其是在代码库很大的时候。浏览代码并添加分配运算符不是我愿意花时间做的事情。

【讨论】:

  • 我希望像这样的问题/答案得到更多关注/支持。比平时有趣得多。
  • 附带说明,这似乎仅在类具有复杂类型(例如由于某种原因)时才需要。简单(包括自定义)类型不会报告此错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
相关资源
最近更新 更多