On Fri, 8 Jul 2022 at 21:47, David Malcolm via Gcc <gcc@gcc.gnu.org> wrote: > > std::unique_ptr is C++11, and I'd like to use it in the gcc/analyzer > subdirectory, at least. The following patch eliminates a bunch of > "takes ownership" comments and manual "delete" invocations in favor > of simply using std::unique_ptr. > > The problem is that the patch makes use of std::make_unique, but that > was added in C++14. > > I've heard that it's reasonably easy to reimplement std::make_unique, > but I'm not sure that my C++11 skills are up to it.
You know we have an implementation of std::make_unique in GCC, with a GCC-compatible licence that you can look at, right? :-) But it's not really necessary. There are only two reasons to prefer make_unique over just allocating an object with new and constructing a unique_ptr from it: 1) avoid a "naked" new in your code (some coding styles like this, but it's not really important as long as the 'delete' is managed automatically by unique_ptr). 2) exception-safety when allocating multiple objects as args to a function, see https://herbsutter.com/gotw/_102/ for details. Irrelevant for GCC, because we build without exceptions. > Is there: > (a) an easy way to implement a std::make_unique replacement > (e.g. in system.h? what to call it?), or If you don't care about using it to create unique_ptr<T[]> arrays, it's trivial: template<typename T, typename... Args> inline typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } To add the overload that works for arrays is a little trickier. > (b) some C++11-compatible way to do the same thing? > without accidentally bringing in C++14 features. std::make_unique doesn't use any C++14 features.