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

前端 未结 19 1293
梦谈多话
梦谈多话 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 08:03

    3 common examples where you have to use new instead of make_...:

    • If your object doesn't have a public constructor
    • If you want to use a custom deleter
    • If you are using c++11 and want to create an object that is managed by a unique_ptr (athough I'd recommend writing your own make_unique in that case).

    In all those cases however, you'd directly wrap the returned pointer into a smart pointer.

    2-3 (probably not so common) examples, where you wouldn't want/can't to use smart pointers:

    • If you have to pass your types through a c-api (you are the one implementing create_my_object or implement a callback that has to take a void*)
    • Cases of conditional ownership: Think of a string, that doesn't allocate memory when it is created from a string litteral but just points to that data. Nowerdays you probably could use a std::variant> instead, but only if you are ok with the the information about the ownership being stored in the variant and is you accept the overhead of checking which member is active for each access. Of course this is only relevant if you can't/don't want to afford the overhead of having two pointers (one owning and one non-owning)
      • If you want to base your ownership on anything more complex than a pointer. E.g. you want to use a gsl::owner so you can easily query it's size and have all the other goodies (iteration, rangecheck...). Admittedly, you'd most likely wrap that in your own class,so this might fall into the category of implementing a container.

提交回复
热议问题