'Creating Your Own Matrix Class

I am creating my own Matrix class. I wrote a copy constructor, but it works correctly only for primitive classes (namely, memory allocation for data). How can the constructor be rewritten (it is possible to overload the new operator) so that it works correctly not only for primitive data types, but also for complex structures (for example, complex classes).

Class fields:

template <typename T>
class Matrix
{
private:
    T *data = nullptr;
    size_t rows;
    size_t cols;

Copy constructor:

Matrix(const Matrix &other) : data(new T[other.rows * other.cols]), rows(other.rows), cols(other.cols)
        {
            for (int i = 0; i < rows * cols; i++)
            {
                data[i] = other.data[i];
            }
        }

It is forbidden to use STL containers, all memory management is manually

Destructor

 ~Matrix() {
     rows = 0;
     cols = 0;
     delete[] data;
}


Solution 1:[1]

The problem is your try to allocate memory for the objects:

: data(new T[other.rows * other.cols])

This default-constructs new objects of type T right away, to which you later on assign values. However it relies on the objects being default constructable, if they aren't, it cannot compile. So you will need to allocate memory explicitly, create the objects via placement new and later on destroy them explicitly alike.

Just a minimalistic demo – you'll need to place the right things at the right places within your constructors and destructor:

template<typename T>
void demo(size_t n, T t[])
{
    auto c = static_cast<T*>
    (
        operator new[]
        (
            n * sizeof(T), static_cast<std::align_val_t>(alignof(T))
        )
    );

    for(size_t i = 0; i < n; ++i)
    {
        // placement new
        new (c + i) T(t[i]);
    }

    for(size_t i = n; i--; )
    {
        // explicitly call destructor
        c[i].~C();
    }
    operator delete[](c);
}

Just the very basics – note that this doesn't consider exceptions occurring during construction/destruction, you'll need appropriate handling for as well.

Solution 2:[2]

You are right, this is currently not supported in Composer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Feng Lu