Search code examples
c++oopcastingmovemove-semantics

Copying vs Moving while casting objects


I am trying to implement a class for linear algebra column vectors. I have the following code snippet, where I try to cast an object without copying anything.

#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>

using namespace std;

class Vector
{
    public:
    std::vector<int> vect;

    public:
    Vector() = default;

    Vector(const Vector& v):vect(v.vect){ };

    Vector(Vector&& v)
    {
        vect.swap(v.vect);
    }

    Vector(const std::vector<int>& v)
    {
        vect = v;
    }

    Vector(std::vector<int>&& v)
    {
        vect.swap(v);
    }

    auto begin()
    {
        return vect.begin();
    }

    auto end()
    {
        return vect.end();
    }
};

class ColumnVector: public Vector
{
    public:
    ColumnVector() = default;

    ColumnVector(const ColumnVector& v)
    {
        this->vect = v.vect;
    }

    ColumnVector(ColumnVector&& v)
    {
        this->vect.swap(v.vect);
    }

    ColumnVector(Vector&& v)
    {
        this->vect.swap(v.vect);
    }
};


int main()
{
    Vector v(vector<int>({ 1, 2, 3, 4, 5 }));

    ColumnVector cv = ( ColumnVector&& )v;

    for ( auto it = v.begin(); it != v.end(); it++ )
        cout << *it << " ";
    // nothing printed -- seems that data have been moved

    for ( auto it = cv.begin(); it != cv.end(); it++ )
        cout << *it << " ";
    // 1 2 3 4 5
}

I try to cast objects without any copying. The speed is essential, so I was wondering if I'm doing it right. Also, guys, do you have any optimization tricks that I can use for this code snippet?

FINAL: I decided to use std::move, which did the job as fast as possible.


Solution

  • You don't need to write the copy and move constructors as the compiler will implicitly generate them if the only behavior is to copy/move the std::vector member.

    By the way, you may want to implement your ColumnVector as a view of the Vector (something like std::string_view) so that there is even no move.