Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++?

前端 未结 19 1282
梦谈多话
梦谈多话 2020-11-22 07:20

Here\'s a notable video (Stop teaching C) about that paradigm change to take in teaching the c++ language.

And an also notable blog post

19条回答
  •  攒了一身酷
    2020-11-22 07:40

    There is still a chance to use malloc/free in C++, as you can use new/delete, and anything higher level wrapping the STL memory templates provided.

    I think in order to really learn C++ and especially understand the C++11 memory templates you should create simple structures with new and delete. Just to better understand how they work. All the smart pointer classes rely on those mechanisms. So if you understand what new and delete does, you are going to appreciate the template more and really find smart ways to use them.

    Today I personally try to avoid them as much as possible, but one main reason is the performance, which you should care if it is critical.

    These are my rules of thumb I always have in mind:

    std::shared_ptr: Automatic management of pointers but due to the reference counting it uses for tracing the accessed pointers, you have a worse performance every time you access these objects. Compared simple pointers I would say 6 times slower. Keep in mind, you can use get() and extract the primitive pointer, and continue accessing it. Of you must be careful with that one. I like to as that as a reference with *get(), so the worse performance is not really a deal.

    std::unique_ptr The pointer access may only happen at one point in the code. Because this template forbids copy, thanks to the r-references && feature, it is much faster than an std::shared_ptr. Because there is still some ownership overhead in this class I would say, they are about twice as slow as a primitive pointer. You access the object than the primitive pointer within that template. I also like to use reference trick here, for less required accesses to the object.

    About performance, it might be true, that those templates are slower, but keep in mind that if you want to optimize software, you should profile first and see what really takes many instructions. It is very unlikely that smart-pointers are the problem, but sure it depends on your implementation.

    In C++ no one should care about malloc and free, but they exist for legacy code. They differ basically in the fact, that they know nothing about c++ classes, which with new and delete operator case is different.

    I use std::unique_ptr and std::shared_ptr in my project Commander Genius everywhere and I'm really happy that they exist. I have not to deal with memory leaks and segfaults since then. Before that, we had our own smart-pointer template. So for productive software, I cannot recommend them enough.

提交回复
热议问题