OwnedArray vs. std::vector

I need to store an array of object of custom type. I wonder what would be the benefit of storing them in OwnedArray instead of in a std::vector? What are the use cases that OwnedArray is the top choice?
I can store my custom type as:

  1. std::vector<MyType>
  2. OwnedArray<MyType*>

I am aware that the OwnedArray stores a list of pointer and will take care of deleting them in its destructor. But it’s unclear to me when is it more sensible to use it instead of the typical std::vector.

Thanks!

std::vector<T> requires T to be copyable or moveable whereas OwnedArray<T> has no constraints on T (AFAIK).

std::vector<T> is more comparable to juce::Array<T>.
juce::OwnedArray<T> is more comparable to std::vector<std::unique_ptr<T>>.

Which is best really depends on your use case. If you want to store copyable or moveable objects, go with std::vector (or juce::Array), if you want to store objects that aren’t copyable or moveable, juce::OwnedArray is the way to go.

2 Likes

You wouldn’t want to do OwnedArray<MyType*> because it already stores pointers and you need to give it pointers to heap allocated objects.

That is, the usage would be like :

OwnedArray<MyType> arr;
arr.add(new MyType());
4 Likes