Is it possible to initialize elements of a unique_ptr array?

115 Views Asked by At

I was using heap memory as part of a small example, and I ended up writing this:

    double* p = new double[4] { 0.0, 1.0, 2.0, 3.0 };
...
    delete[] p;

Later, I wanted to upgrade this to a std::unique_ptr:

    std::unique_ptr<double[]> arrp(new double[4] { 0.0, 1.0, 2.0, 3.0 });
...

(no need for delete[]).

Of course, it is always better to use std::make_unique rather than new, but how can initialize an array of elements with std::make_unique?

1

There are 1 best solutions below

5
alfC On

To answer my own question, here is a bad, no-good, inefficient implementation that I do not necessarily want to use.

At best it would clarify what I want in the question.

#include <memory>
#include <utility>
#include <type_traits>

namespace xtd {
    template<class T, class T2>
    auto make_unique(std::initializer_list<T2> il) {
        if constexpr(std::is_array_v<T>) {
            std::unique_ptr<T> ret(new std::remove_extent_t<T>[il.size()]);
            std::copy(il.begin(), il.end(), ret.get());  // not std::uninitialized_copy
            return ret;
        } else {
            return std::make_unique<T>(il);
        }
    }
}

int main() {
    std::unique_ptr<double[]> p(new double[4] { 0.0, 1.0, 2.0, 3.0 });

    auto q = xtd::make_unique<double[]>({0.0, 1.0, 2.0, 3.0});
}

https://godbolt.org/z/d11h8WhEo