Opencv的文档中提到,目前没有移动构造函数,因此类似于cv::Mat A=std::move(some_other_cv_mat)
这样的语句并没有太多意义。我的当前(并且是天真的)解决方案是从cv::Mat
派生一个类,并实现以下移动构造函数:
namespace cv
{
//matrix object derived from cv::Mat
class Mvbl_Mat final: public Mat
{
public:
//constructors
Mvbl_Mat(){};
Mvbl_Mat(int rows, int cols, int type, const Scalar &s):Mat(rows, cols, type, s){}
//destructor
~Mvbl_Mat(){};
//move constructor
Mvbl_Mat(Mvbl_Mat && other) noexcept
{
this->data=other.data;
other.data=nullptr;
}
//move assignment operator
Mvbl_Mat & operator=(Mvbl_Mat && other)
{
this->data=other.data;
other.data=nullptr;
return *this;
}
};
}
虽然目前这在我面临的有限问题上是行之有效的,但显然存在许多限制,解决方案远非理想。那么,模拟cv::Mat
的移动语义的最佳方法是什么?
cv::Mat
来说,move
意义不大,因为复制构造函数不会复制数据。而您的移动构造函数可能会破坏引用计数器。 - Holtshared_ptr
),move
也非常有意义,甚至可以说更有意义。想象一下,你希望将一个Mat
对象传递给一个函数,但在调用后自己不需要这个Mat
对象了。如果没有move
,你就必须一直保持对这个对象的引用(以及内存)直到函数返回。而有了move
,你就有机会在这种情况下在函数内部重复使用内存。 - pwuertz