0

It seems that I'm missing something obvious, but I can't find an elegant solution of the following problem.

I need to create a collection of objects, where some of them are pointed by shared_ptr (and thus owned by container itself) and some by weak_ptr (thus not owned).

What is the best way of doing this? So far I came up with rather ugly solution like this:

template <class Data>
struct holder {
  shared_ptr<Data> owned;
  weak_ptr<Data> borrowed;

  shared_ptr<Data> get(){
    if(owned) 
       return owned;
    else
       return borrowed.lock();
  }
}
...
vector<holder<MyData>> vec;

I can overload assignment for shared_ptr and weak_ptr and also dereferencing to make it "transparent" to store both kind of things but all this looks complex and non-optimal.

Is there any better way of doing this?

yesint
  • 145
  • 9
  • What is so ugly about it? – Michael Chourdakis Feb 09 '20 at 08:16
  • 1
    You want to store 2 distinct types in one container. The only way to achieve this is to make a container of an union type of some sort (like `std::variant`) or a custom class of your own making. – oakad Feb 09 '20 at 08:52
  • @MichaelChourdakis at lest doubling the storage size due to two pointers per item instead of one. – yesint Feb 09 '20 at 09:00
  • @yesint so? Is the size so important? You need two separated distinct objects. You can use `std::variant` or `std::any` if you want one or the other, but not both. But using repeatedly the members of variant or any just to reduce the size is not that nice. Besides, you are going to check the return value to see if weak_ptr's lock succeeded, which is tedious. – Michael Chourdakis Feb 09 '20 at 09:08

0 Answers0