I often need to deal with dynamically-allocated arrays in C++, and hence rely on Boost for scoped_array, shared_array, and the like. After reading through Stroustrup's C++11 FAQ and the C++11 Reference Wiki, I could not find a suitable replacement for these dynamic array wrappers that is provided by the C++11 standard. Is there something that I have overlooked, or do I have to continue relying on Boost?
Asked
Active
Viewed 1.3k times
2 Answers
50
There is a specialization of unique_ptr
, like unique_ptr<T[]>
.
#include <iostream>
#include <memory>
struct test
{
~test() { std::cout << "test::dtor" << std::endl; }
};
int main()
{
std::unique_ptr<test[]> array(new test[3]);
}
When you run it, you will get this messages.
test::dtor
test::dtor
test::dtor
If you want to use shared_ptr
, you should use std::default_delete<T[]>
for deleter since it doesn't have one like shared_ptr<t[]>
.
std::shared_ptr<test> array(new test[3], std::default_delete<test[]>());

Inbae Jeong
- 4,053
- 25
- 38
-
That specialization also provides `T& operator[](size_t)` to access the members. – Andreas Haferburg Nov 20 '19 at 12:47
0
So far as vectors are intended as array wrappers, what if you use any suitable smart pointer with the vector as inner object?

Yury Schkatula
- 5,291
- 2
- 18
- 42
-
vector::emplace_back() and vector::push_back() won't work if the element type is not copy-constructible. I don't know about initializing with an initializer list, but i suspect that has the same problem. – Joshua Chia Mar 27 '15 at 10:20
-
Yep, you're right, in that case we need to wrap such non-copyable things with extra wrapper, that tends to be some overkill indeed :) – Yury Schkatula Mar 27 '15 at 12:06