I\'ve been using C++ for a short while, and I\'ve been wondering about the new keyword. Simply, should I be using it, or not?
1) With the new keywo
The short answer is: if you're a beginner in C++, you should never be using new
or delete
yourself.
Instead, you should use smart pointers such as std::unique_ptr
and std::make_unique
(or less often, std::shared_ptr
and std::make_shared
). That way, you don't have to worry nearly as much about memory leaks. And even if you're more advanced, best practice would usually be to encapsulate the custom way you're using new
and delete
into a small class (such as a custom smart pointer) that is dedicated just to object lifecycle issues.
Of course, behind the scenes, these smart pointers are still performing dynamic allocation and deallocation, so code using them would still have the associated runtime overhead. Other answers here have covered these issues, and how to make design decisions on when to use smart pointers versus just creating objects on the stack or incorporating them as direct members of an object, well enough that I won't repeat them. But my executive summary would be: don't use smart pointers or dynamic allocation until something forces you to.