TheDoomDestroyer
TheDoomDestroyer

Reputation: 3005

shared_ptr to an array

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]>();

Upvotes: 12

Views: 17670

Answers (4)

chang jc
chang jc

Reputation: 529

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?

Upvotes: 0

Stanisław Fortoński
Stanisław Fortoński

Reputation: 348

I think better for this problem is unique_ptr template.

int amount = 10;
std::unique_ptr<int[]> name(new int[amount]);

Upvotes: 0

21koizyd
21koizyd

Reputation: 2003

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;

Upvotes: 22

AndyG
AndyG

Reputation: 41100

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.

Upvotes: 6

Related Questions