简体   繁体   中英

C++ std::array to vector of shared_ptr

What is the most idiomatic way to convert it?

std::array<SomeType,SIZE> arr;

std::vector<shared_ptr<SomeType>> vec;  // <--- want to fill with pointers
                                        //      to items in arr

Second question - is it possible to create a shared_ptr to objects in a stack-allocated array ? Will the pointer targets be "freed" once vec is destroyed?

EDIT

I need something like 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 and assign to groups; set next-pointers in elems:
  //  group1: &elem10
  //  group2: &elem8 &elem5
  //  group3: &elem2 &elem7 &elem3
  //  group4: &elem4 &elem9 &elem1 &elem6

  // at some point:
  //  save or load all elems and groups,
  //  preserving pointers elem->elem, group->elem
}

If you want a shared_ptr to an object, then you should ensure that the object really is managed by a shared_ptr . Playing games with this is dangerous and can lead to undefined behaviour. In your case, the trick is to manage the array itself with a shared_ptr . That will let you retrieve a valid shared_ptr to any of its elements.

auto elems = std::make_shared<std::array<Element,10>>();

You can then use shared_ptr 's aliasing constructor to create shared_ptrs to the individual elements. If you want to stick those shared_ptrs in a vector , you could do something like 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 that one (possibly unintended) consequence of this is that your entire elements array will continue to exist as long as you have a shared_ptr to one of its members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM