Should smart pointers be preferred over new and delete keywords?

Im on chapter 11.9 of learncpp and i see that its going to be teaching about using new and delete, but i heard its better to use smart pointers instead. I can understand teaching it since people learning may be working with old code, but since im only going to be writing modern C++ and not working in the programming field with other peoples code, i wondered if it would be find to just skip those sections? Im strictly going to be writing my own code so i dont need to know backwards compatible stuff for older versions of C++.

There was a section about how to use C style strings and i skipped that too since it recommened not using it and i dont want to even bother with stuff i wont need.
Last edited on
It depends.

You should know how to use new and delete, after all they are used in legacy code. A lot.

For that matter you should learn how to use the C library manual memory management techniques. malloc/calloc/realloc/free.

When crafting new code consider using smart pointers before using manual memory management.

The smart pointers relieve you of the burden of worrying about managing memory, but they do introduce a slight overhead to your programs. Most times that won't be noticeable.

Similar overhead can result from using C++ containers vs. using old school arrays.

There was a section about how to use C style strings and i skipped

Don't skip it. To understand how C++ does its 'magic', and when dealing with legacy code, knowing how things are done under the hood is very helpful.

Legacy code can be something as simple as using (and understanding) 3rd party libraries.
At least do the basics. An hour or two of your time will help a lot when you run into the ideas in languages that don't have smart pointers, like C, or even if you run into things like library calls, eg it gives you a hint at what microsoft's gcnew() ? function does (esp if you pick up that gc is garbage collection), or if in c#, you see it all the time (eg var dict = new Dictionary<string, int>() ) and because some of it is done for you, they often don't explain it well in other languages, whereas a C or older C++ tutorial on it gets you down and dirty with what is going on. It may give you insights, like how a vector works inside, or even better, how a smart pointer class works. If you really want to pull it all together, an exercise for you: try writing a templated smart* class of your own that does something like free its memory when it deconstructs, and then improve on that, maybe do a simple reference counting and tracking system, get a feel for what you are paying out in performance when you use the smart ones or libraries.

Bottom line is that you won't use it much most likely, but a small time investment would give you a great deal of useful info that may help you and certainly won't hurt you.
Last edited on
Topic archived. No new replies allowed.