12

How can you dynamically allocate "n number of elements" to which a shared_ptr will point to?

I was able to create a static array that a shared pointer will point to, but I'd like the user to enter a number and then allocate n number of elements.

shared_ptr<int[10]> p = make_shared<int[10]>();
TheDoomDestroyer
  • 2,434
  • 4
  • 24
  • 45

4 Answers4

21

You should create that shared_ptr like that

std::shared_ptr<int> sp( new int[10], std::default_delete<int[]>() );

You must give other deleter to shared_ptr

You can't use std::make_shared, because that function gives only 1 parameter, for create pointer on array you must create deleter too.

Or you can use too (like in comments , with array or with vector, which has own deleter)

std::shared_ptr<std::array<int,6>> ptr(std::make_shared<std::array<int, 6>>(std::array<int, 6>()));

How get particular element? Like that

std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
sp.get()[0] = 5;
std::cout << sp.get()[0] << std::endl;
21koizyd
  • 1,843
  • 12
  • 25
5

The language currently lacks the ability to use make_shared to accomplish that. It is addressed in P0674. Pretty sure it's going to make its way into the language, though it won't be C++11.

The wording will allow you to say

auto p = std::make_shared<int[10]>()

or

auto p = std::make_shared<int[]>(10)

Until C++20 (or whenever the proposal gets officially standardized), you're stuck with using the new syntax as linked in 21koizyd's answer.

AndyG
  • 39,700
  • 8
  • 109
  • 143
0

I think better for this problem is unique_ptr template.

int amount = 10;
std::unique_ptr<int[]> name(new int[amount]);
Stan Fortoński
  • 348
  • 6
  • 13
0

I found the form below is wrong.

std::shared_ptr<std::array<int,6>> ptr(std::make_shared<std::array<int, 6>>(std::array<int, 6>()));

It invokes two times destructor.

If your input is not native type such as int, it will lead to a crash.

One can try it.

std::shared_ptr<std::array<int,6>> ptr(std::make_shared<std::array<int, 6>>());

Maybe the claim above is correct?

Is there anyone know why it invokes two times of destructor?

any thoughts?

chang jc
  • 489
  • 8
  • 16
  • While that certainly takes over the make_shared function unable to be used for arrays, it certainly doesn't help with the question where the user should be allowed to decide how many elements he wants the array to have. Hence the constructor workaround being used as the best one until C++20, – TheDoomDestroyer Dec 09 '17 at 18:17