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]>();
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With