pointers - C++ std::array to vector of shared_ptr -
what idiomatic way convert it?
std::array<sometype,size> arr; std::vector<shared_ptr<sometype>> vec; // <--- want fill pointers // items in arr
second question - possible create shared_ptr
objects in stack-allocated array
? pointer targets "freed" once vec
destroyed?
edit
i need this
class element { element *next; } class group { std::vector<element*> elems; } int main() { ... std::array<element,10> elems = {...}; std::array<group,4> groups = {...}; // shuffle elems , assign groups; set next-pointers in elems: // group1: &elem10 // group2: &elem8 &elem5 // group3: &elem2 &elem7 &elem3 // group4: &elem4 &elem9 &elem1 &elem6 // @ point: // save or load elems , groups, // preserving pointers elem->elem, group->elem }
if want shared_ptr
object, should ensure object managed shared_ptr
. playing games dangerous , can lead undefined behaviour. in case, trick manage array shared_ptr
. let retrieve valid shared_ptr
of elements.
auto elems = std::make_shared<std::array<element,10>>();
you can use shared_ptr
's aliasing constructor create shared_ptrs
individual elements. if want stick shared_ptrs
in vector
, this:
std::vector<std::shared_ptr<element>> v; v.reserve(elems->size()); std::transform( elems->begin(), elems->end(), std::back_inserter(v), [&elems] (element& e) { return std::shared_ptr<element>{ elems, &e }; });
note 1 (possibly unintended) consequence of entire elements array continue exist long have shared_ptr
1 of members.
Comments
Post a Comment