带有已删除副本构造函数的Intel 13.1.2中不良C ++行为的解决方法

时间:2018-08-08 19:52:15

标签: c++ c++11

我一直坚持支持Intel 13.1.2,它名义上符合C ++ 11,但是此代码:

#include <algorithm>

struct moveonly {
  moveonly()                =default;
  moveonly(const moveonly&) =delete;
  moveonly(moveonly&& other) { member = std::move(other.member); }

private:
  int member = 0;
};

template <typename T>
struct holds {
  operator T&&() { return std::move(t); }
  T t;
};


int main() {
  holds<moveonly> m;
  moveonly a = m;
}

无法编译:

 ╰─▸ icc -std=c++11 test.cc -o test
test.cc(21): error: function "moveonly::moveonly(const moveonly &)" (declared at line 5) cannot be referenced -- it is a deleted function
    moveonly a = m;
                 ^

test.cc(21): error: function "moveonly::moveonly(const moveonly &)" (declared at line 5) cannot be referenced -- it is a deleted function
    moveonly a = m;
                 ^

compilation aborted for test.cc (code 2)

假设我无法使该类可复制,并且想保留转换运算符,有人可以提出解决方法吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试使右值明确:

moveonly a = std::move(m);

可能的是,显式强制转换也有帮助:

moveonly a = static_cast<moveonly&&>(m);

显式调用强制转换运算符:

moveonly a = m.operator moveonly&&();

如果全部失败,则退回到C ++ 11之前的版本意味着:

struct holds
{
    operator T&&() { return std::move(t); }
    T t;
    swap(T& tt)
    {
        swap(t, tt);
    }
};

为moveonly定义了适当的交换,因此您可以:

moveonly a;
m.swap(a);