3 ms·
#1 should really say, "Avoid new and delete." new and delete are for experts. The average C++ programmer should go nowhere near them. If heap memory is used
by Suncho 12y ago
#1 should really say, "Avoid new and delete." new and delete are for experts. The average C++ programmer should go nowhere near them. If heap memory is used internally by a class that was written by someone who knew what they were doing, then fine. Use your std::vector. But new and delete are huge red flags in code.
- TillE 12y agoIt's fine to use new as long as you're immediately sticking the result in a smart pointer. But yes, delete should be very very rare in modern C++ code.
- hendzen 12y agoWith std::make_shared, and the addition of std::make_unique in C++14, you shouldn't ever need to use new for this purpose either.
- Suncho 12y agoIt depends. The trick to using new correctly is to put it in a function whose sole purpose is to immediately store new's result in the smart handle. I.E. You're writing a function that's analogous to the make_unique function. You might need to do this if you're implementing your own smart handle or writing a factory function for a class with a private constructor (make_unique will not work). Off the top of my head, I can't think of any good reasons to use delete.
- lomnakkus 12y agoIf your handles are pointer types, you should still use unique_ptr, you just need to give it a custom "deleter". (Of course you should probably still encapsulate this in a function like make_xxx() just to avoid the potential mistake of not supplying the correct deleter everywhere.)
- toolslive 12y agoand yet, "new" and "delete" are amongst the very first things covered in every C++ tutorial book. for example in Stroustrup's "A tour of C++", it's covered in section 1.6. without any remark about shared_ptr and friends.