I'm trying to have a struct take possession of a pointer to an array of pointers to objects on the heap. In order to not have to worry about deleting these objects I want to use smart pointers. However, I can't seem to find a correct syntax to do so...
This is what (I think) I want to achieve:
const std::unique_ptr<(*Position)[]> entity_position;
And then receive a unique_ptr<*Position[]>
as a parameter of the struct constructor. But I am getting an expected expression
error on the closing ']'.
I have looked at std::unique_ptr with array pointer (to confirm delete[]
would indeed be called) and Get array of raw pointers from array of std::unique_ptr but I haven't fully understood what this last one was trying to achieve.
Here is a simplified version of the code I am writing:
#include <memory>
#include "Position.hpp"
struct myStruct final : public baseStruct{
const std::unique_ptr<(*Position)[]> pos_pointer_array;
myStruct(std::unique_ptr<(*Position)[]> ptr_to_get): pos_pointer_array(ptr_to_get){}
}
Any help much appreciate ! (And disclaimer: I haven't really used smart pointers before...)
A unique_ptr
to an array will only clean up the array, but if the elements are pointers to objects stored elsewhere (presumably on the heap) then those objects are not cleaned up automagically.
It seems you rather want a
std::vector< std::unique_ptr<Position>>
or a unqiue_ptr
to an array with a custom deleter that also deletes the elements. On the other hand, if the array owns the Position
s chances are high that all you need is a
std::vector<Position>