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

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

    You can still use new and delete if we want to create our own lightweight memory allocation mechanism. For example

    1.Using In-Place new : Generally used for allocating from preallocated memory;

    char arr[4];
    
    int * intVar = new (&arr) int; // assuming int of size 4 bytes
    

    2.Using Class Specific Allocators : If we want a custom allocator for our own classes.

    class AwithCustom {
    
    public:
        void * operator new(size_t size) {
             return malloc(size);
        }
    
        void operator delete(void * ptr) {
              free(ptr);
        }
    };
    

提交回复
热议问题