在来自 stl 向量的派生 class 中实现移动语义
Implement the move semantic in a derived class from stl vector
我有以下 class 继承了 STL 向量:
class Vec : public vector<int> {
public:
Vec() : vector<int>() {}
Vec(size_t N) : vector<int>(N) {}
Vec(Vec&& v) : vector<int>(v) {}
Vec(const Vec&) = delete;
Vec& operator = (const Vec&) = delete;
};
基本上,Vec
是 STL 向量的包装器,其中禁用了 copy
构造函数和赋值。但是,看起来移动构造函数无法通过以下方式正常运行:
Vec a(100);
Vec b(move(a))
cout << a.size() << " " << b.size(); // here I got "100 100"
我的 Vec
包装器有什么问题吗?另外,如何为我的 Vec
class 实现移动分配,以便 Vec b = a
由移动分配?我在想象类似下面的东西,但它不起作用:(
Vec& operator = (Vec&& rhs) {
return move(*this);
}
又抓到一个。在实现移动语义时,我们是否应该始终避免使用 const
关键字?任何帮助将不胜感激。
Vec(Vec&& v) : vector<int>{std::move(v)} // You missed a `std::move` here
{
}
Vec& operator=(Vec&& v)
{
vector<int>::operator=(std::move(v)); // Selects base class function
return *this;
}
在您的 Vec 移动构造函数中,您使用的是矢量复制构造函数。
只是 chaage 这个:
Vec(Vec&& v) : vector<int>(move(v)) {};
它将正常工作。
我有以下 class 继承了 STL 向量:
class Vec : public vector<int> {
public:
Vec() : vector<int>() {}
Vec(size_t N) : vector<int>(N) {}
Vec(Vec&& v) : vector<int>(v) {}
Vec(const Vec&) = delete;
Vec& operator = (const Vec&) = delete;
};
基本上,Vec
是 STL 向量的包装器,其中禁用了 copy
构造函数和赋值。但是,看起来移动构造函数无法通过以下方式正常运行:
Vec a(100);
Vec b(move(a))
cout << a.size() << " " << b.size(); // here I got "100 100"
我的 Vec
包装器有什么问题吗?另外,如何为我的 Vec
class 实现移动分配,以便 Vec b = a
由移动分配?我在想象类似下面的东西,但它不起作用:(
Vec& operator = (Vec&& rhs) {
return move(*this);
}
又抓到一个。在实现移动语义时,我们是否应该始终避免使用 const
关键字?任何帮助将不胜感激。
Vec(Vec&& v) : vector<int>{std::move(v)} // You missed a `std::move` here
{
}
Vec& operator=(Vec&& v)
{
vector<int>::operator=(std::move(v)); // Selects base class function
return *this;
}
在您的 Vec 移动构造函数中,您使用的是矢量复制构造函数。 只是 chaage 这个:
Vec(Vec&& v) : vector<int>(move(v)) {};
它将正常工作。