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

前端 未结 19 926
梦谈多话
梦谈多话 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:42

    Adding to other answers, there are some cases where new/delete make sense -

    1. Integrating with a 3rd party library which returns the raw pointer and expect you return the pointer to the library once you are done (The library has its own memory management functionality).
    2. Working on resource constrained embedded device where memory (RAM/ROM) is a luxury (even a few kilobytes). Are you sure you want to add more runtime (RAM) and compiled (ROM/Overlay) memory requirement to your application or you want to program carefully with new/delete?
    3. From purist point of view, in some cases smart pointers won't work intuitively (due to their nature). For example, for builder pattern you should to use reinterpret_pointer_cast, if you are using smart pointers. Another case is where you need to cast from a base type to a derived type. You put yourself danger if you get the raw pointer from smart pointer, cast it and put it in another smart pointer and ended up freeing the pointer multiple times.

提交回复
热议问题