我有一个函数处理一个只能移动的实例,它是一个包装其他东西的包装器。该对象提供了访问包装对象的方法以及一些要求它不可复制的检查。 (用例是一个值表,其中包装器的dtor应声明所有值都已被访问)
我从包装类型定义了一个自定义ctor并实现了移动ctor / assignment。
但是由于尝试复制,我收到错误:error: 'Movable::Movable(Movable&)' is private within this context
它在C ++ 11中运行良好但我需要可移植到C ++ 03。如果没有显式的包装器实例化并将其移动到函数中,我该怎么做呢?
MWE:
#include <boost/move/move.hpp>
#include <iostream>
class Movable{
BOOST_MOVABLE_BUT_NOT_COPYABLE(Movable)
public:
int i;
Movable(int j):i(j){}
Movable(BOOST_RV_REF(Movable) other) // Move constructor
: i(boost::move(other.i))
{}
Movable& operator=(BOOST_RV_REF(Movable) other) // Move assignment
{
if(this != &other)
i = boost::move(other.i);
return *this;
}
};
void bar(Movable mov){
mov.i = 22;
std::cout << mov.i;
}
int main(int argc, char* argv[])
{
bar(5);
return 0;
}
问题似乎是隐式转换构造函数干扰了复制构造函数抑制。
要么使用
Movable m(5);
bar(boost::move(m));
要么
bar(Movable(5));
确保选择显式构造函数。显然,这意味着你甚至可以标记它explicit
:
#include <boost/move/move.hpp>
#include <iostream>
class Movable{
BOOST_MOVABLE_BUT_NOT_COPYABLE(Movable)
public:
int i;
explicit Movable(int j):i(j){}
Movable(BOOST_RV_REF(Movable) other) // Move constructor
: i(boost::move(other.i))
{}
Movable& operator=(BOOST_RV_REF(Movable) other) // Move assignment
{
if(this != &other)
i = boost::move(other.i);
return *this;
}
};
void bar(Movable mov){
std::cout << mov.i << " ";
mov.i = 22;
std::cout << mov.i << "\n";
}
int main() {
Movable m(5);
bar(boost::move(m));
bar(Movable(6));
}
打印
5 22
6 22