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

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

    I'm going to be contrarian, and go on record as saying "no" (at least to the question I'm pretty sure you really intended to ask, for most of the cases that have been cited).

    What seem like obvious use-cases for using new and delete (e.g., raw memory for a GC heap, storage for a container) really aren't. For these cases, you want "raw" storage, not an object (or array of objects, which is what new and new[] provide respectively).

    Since you want raw storage, you really need/want to use operator new and operator delete to manage the raw storage itself. You then use placement new to create objects in that raw storage, and directly invoke the destructor to destroy the objects. Depending on the situation, you might want to use a level of indirection to that though--for example, the containers in the standard library use an Allocator class to handle these tasks. This is passed as a template parameter, which provides a customization point (e.g., a way to optimize allocation based on a particular container's typical usage pattern).

    So, for these situations, you end up using the new keyword (in both the placement new and the invocation of operator new), but not something like T *t = new T[N];, which is what I'm pretty sure you intended to ask about.

提交回复
热议问题