在从 stl 向量的派生类中实现移动语义

Implement the move semantic in a derived class from stl vector

本文关键字:实现 移动 语义 派生 stl 向量 在从      更新时间:2023-10-16

我有以下继承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类的移动分配,以便通过移动分配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 移动构造函数中,您正在使用矢量复制构造函数。只是追查这个:

    Vec(Vec&& v) : vector<int>(move(v)) {};

它会正常工作。