About the usage of new and delete, and Stroustrup's advice

前端 未结 3 609
旧时难觅i
旧时难觅i 2021-02-01 03:32

About the usage of new and delete, and Stroustrup\'s advice...

He says something like (but not exactly, this is from my notes of his book):

A rule

3条回答
  •  星月不相逢
    2021-02-01 04:17

    Seems more like a poll than a question but here it goes: in application code I generally don't use new at all. Due to our coding guidelines the code does use pointer but none of these "naked" pointers is actually transfering ownership. All objects are owned by some other object.

    To be fair, when objects need to be allocated the allocation generally uses something morally equivalent to std::make_shared(...) which sometimes does show up in application code. One major reason for this rather thorough absence of new (or similar) is that objects are generally allocated using stateful allocators and not doing so via a resource manager actually happens to be fairly complicated. Thus, there is little place for direct memory allocation using new or a placement version thereof in application code.

    In some infrastructure code, especially when creating custom containers the situation is slightly different: there is memory allocated (from allocators and initialized using placement new) there. However, even there any result from memory allocation and initialization of objects is immediately passed on to resource managers. Basically, I can't cope with explicit resource management and using resource managers just reliefs me of the necessary work.

提交回复
热议问题