Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr to an array

Tags:

c++

c++11

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]>();
like image 708
TheDoomDestroyer Avatar asked Jul 06 '17 13:07

TheDoomDestroyer


2 Answers

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;
like image 169
21koizyd Avatar answered Oct 12 '22 11:10

21koizyd


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.

like image 23
AndyG Avatar answered Oct 12 '22 13:10

AndyG