HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Simple resizable array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysimpleresizable

Problem

In some (lower-level) parts of my codebase I often have the need to allocate resizable array storage for certain objects, that usually are not default-constructible.

I created a simple class using std::aligned_storage and I was wondering if it's safe and if it can be improved.

The user of the class has to keep track of the current capacity.

template class ResizableArray
{
    private:
        using TStorage = std::aligned_storage_t;
        TStorage* data{nullptr};

    public:
        ~ResizableArray() { delete[] data; }

        void resize(std::size_t mSizeOld, std::size_t mSizeNew)
        {
            auto newData(new TStorage[mSizeNew]);
            for(auto i(0u); i (data[mIdx]); }

    const auto& operator[](std::size_t mIdx) const noexcept 
    { return reinterpret_cast(data[mIdx]); }
};


Example usage:

int main()
{
    ResizableArray a;

    // Resize array capacity from 0 to 10
    a.resize(0, 10);

    for(auto i(0u); i < 10; ++i)
        new (&a[i]) Thing{/* something */};

    return 0;
}

Solution

I see a couple of problems:

-
If you ever shrink the array, the loop for copying the elements will overrun the bounds of newdata because the index runs from 0 to mSizeOld.

-
You don't store the size of the array in the class, so code like this will lose data:

ResizeableArray a;
a.resize(0, 10);
// Populate the array
a.resize(0, 11);
// Now a is empty again because resize() uses the first argument.


This might be intentional — to allow you to start over with a fresh set of data &mdash but if so, resize() should be commented to say that.

Code Snippets

ResizeableArray<Thing> a;
a.resize(0, 10);
// Populate the array
a.resize(0, 11);
// Now a is empty again because resize() uses the first argument.

Context

StackExchange Code Review Q#67114, answer score: 5

Revisions (0)

No revisions yet.