Unique_ptr, it's pants, i don't like it!

No - if the vector is “too small” it’ll be enlarged. If there’s not enough memory, you’ll get an exception but then you’re likely in much deeper trouble. Trouble that could maybe be avoided by calling vec.reserve() before constructing new elements in place.

I use std::make_unique<> and then vec.back() after adding a new element. That makes ownership clear.

Switching everything from ScopedPointer to std::unique_ptr has been painful in the beginning, but overall the design is better and if you plan to ever code c++ outside Juce it’s something you better get used to anyway. Once you also start using juce:: prefixes everywhere, the extra verbosity doesn’t look out of place anymore ;).

Oh, sorry, I pasted it wrong obviously, you are right :slight_smile: It should be vice versa. std::make_unique should be used!

Of course you are right, I wanted just to warn that because emplace_back can create an object, so instead of using make_unique it could be tempting to use raw pointer instead with emplace_back. But then it can leak. In C++14 things are simpler with std::make_unique as you stated.

If your vector can’t expand enough to add one more pointer I think the leak is the least of your worries …?

1 Like

Exactly :slight_smile: This discussion is kind of fun. I tell you that for storing components I still use OwnedArray.

1 Like

OwnedArray is my best friend most of the time. :slight_smile:

Arriving a bit late to the discussion here, but having battled with the Rust compiler last year, I now appreciate that it will prevent mistakes such as use after move/delete (as well as not allow things that to a C/C++ programmer seem perfectly OK). I wonder if the C++ compiler will ever get clever enough to prevent mistakes like this?

At least code analyzers will catch it, like Xcode Analyze:

7 Likes