Is it bad (or even dangerous) to random_shuffle vector of shared_ptrs?

486 views Asked by At
using namespace std;
vector< shared_ptr<MyObject> > objects;

// objects gets filled in by something

random_shuffle(objects.begin(), objects.end());

Is this bad or inefficient for any reason? Is there a better way of doing it? (I want my array of smart pointers sorted randomly)

EDIT: I'm asking because there are going to be a lot of swaps, and since I don't know the implementation behind the scenes I was wondering if it might be possible that:

  • lots of reference counts could be going up and down like crazy, impacting performance
  • even worse, is there a possibility of cyclic references that could cause memory leaks
2

There are 2 answers

10
lisyarus On BEST ANSWER

No, there is nothing bad or inefficient in this.

std::random_shuffle only swaps the elements of the cointainer in some random way. std::swap is specialized for std::shared_ptr's, so it is safe and as efficient as swapping two pairs of raw pointers, without

lots of reference counts could be going up and down like crazy, impacting performance

Even if no such specialization existed, it would still be safe and efficient, as it would only rely on moving shared pointers, not copying them (and moving a std::shared_ptr does not affect reference counter).

As for cyclic references, if you had some - they will still be present, if you didn't - swap cannot introduce new.

0
Steephen On

The requirements for std::random_shuffle usage is elements should be ValueSwappable and the container should have a random_access iterator support. std::shared_ptrs are ValueSwappable and std::vector has random access iterators. So it should be safe and it will not make any change in std::shared_ptr::use_count().

http://en.cppreference.com/w/cpp/concept/RandomAccessIterator

http://en.cppreference.com/w/cpp/concept/ValueSwappable