lundi 28 décembre 2015

Initialize custom array class without creating copies

I wrote a custom array container, as most C++ libraries including std::array and std::iterator are not available for the target (embedded). The template class is mostly working as intended.
However I did not manage to set up a constructor, which can initialize the whole array without creating copies. I tried several constructors including passing by reference. The one shown will create a copy and has issues if the size of the passed array does not match the one of my class.

Language features up to C++11 are supported in the environment, but no std libraries are available. Therefore the answers to similar questions could not be used.

The sourcecode of the template class:

template<typename T, typename sizetype, sizetype SIZE>
class mArray
{
private:
    T _elements[SIZE]; ///< Array of SIZE elements of Type T
    static_assert( SIZE > 0, "Size must be > 0"); // Discourage empty array
public:
    mArray(){};
    mArray(T initArr[SIZE])
    {
        sizetype index = 0;
        for (auto element : _elements)
        {
            _elements[index] = initArr[index]; //
            ++index;
        }
    }
    T* begin()
    {
        return &_elements[0]; // Pointer to first _element
    }
    T* end()
    {
        return &_elements[SIZE]; // Pointer behind last _elements
    }
    T front()
    {
        return _elements[0]; // Return first element of _elements
    }
    T back()
    {
        return _elements[SIZE-1]; // Return last element of _elements
    }
    T at(sizetype pos)
    {
        static_assert( pos > SIZE, "pos must be < SIZE");
        return _elements[pos];
    }
    T operator[](sizetype pos)
    {
        return _elements[pos];
    }
    T* data()
    {
        return *_elements;
    }
    sizetype size()
    {
        return SIZE;
    }
};

How can I improve the constructor to avoid creating copies?

Aucun commentaire:

Enregistrer un commentaire