Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++11 have wrappers for dynamically-allocated arrays like Boost's scoped_array?

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?

like image 995
void-pointer Avatar asked Dec 24 '11 11:12

void-pointer


1 Answers

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[]>());
like image 135
Inbae Jeong Avatar answered Oct 17 '22 06:10

Inbae Jeong