Search code examples
c++c++11inheritancemove

Implement the move semantic in a derived class from stl vector


I have the following class which inherits the STL vector:

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;
};

Basically, Vec is a wrapper of STL vector in which the copy constructor and assignment are disabled. However, it looks like the move constructor doesn't function correctly by the following:

Vec a(100);
Vec b(move(a))
cout << a.size() << " " << b.size();  // here I got "100 100"

Is there anything wrong in my Vec wrapper? Also, how can I implement the move assignment for my Vec class such that Vec b = a is assigned by move? I am imagining something like the following but it doesn't work :(

Vec& operator = (Vec&& rhs) {
  return move(*this);
}

One more catch. When implementing move semantics, should we always avoid using const keyword? Any help will be greatly appreciated.


Solution

  • 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;
    }
    

    Demo