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
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 forstd::shared_ptr
's, so it is safe and as efficient as swapping two pairs of raw pointers, withoutEven 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.