3 ms·
Why everyone hating new/delete so much? Instead of this headache with smart pointers and all complicated stuff they bring, clear and easily understandable memor
by nokeya 10y ago
Why everyone hating new/delete so much?
Instead of this headache with smart pointers and all complicated stuff they bring, clear and easily understandable memory management.
- zanny 10y agoBecause as a computer scientist the last thing you should ever want to do is to do something manually. Because when you do something by hand, every time - especially something as simple as heap allocated objects - you will do it wrong all the time. And memory management is complicated, even if the primitives are not. So when you combine something one level of indirection away complex with a ton of boilerplate you get constant problems, which 25 years of C++ have demonstrated repeatedly in the context of raw memory operators. These smart pointers, in reality, are not a headache. You want to make a heap object? make_unique. You want to pass it around? Go for it. You want to pass ownership? std::move it. And only in the extremely rare case where you have multiple objects of non-deterministic lifetime that need to both access the exact same data structure, then you pull out shared_ptr and deal with the synchronization. But unique_ptr, by itself, is probably the most productive addition to C++ period. More than the STL, more than templates, if you use it correctly and design your code properly, it can replace every heap allocation and drastically reduce code complexity.