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

前端 未结 3 612
旧时难觅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:16

    It's a great rule. In fact, you can avoid using new in arguments to smart pointers by using the appropriate make_ functions. For example, instead of:

    std::shared_ptr p(new int(5));
    

    You can often do:

    auto p = std::make_shared(5);
    

    This also has the benefit of being more exception safe. While a std::make_unique doesn't yet exist, it is planned to make its way into C++14 (it is already in the working draft). If you want it now, there are some existing implementations.

    You can go a step further and even avoid using new and delete in constructors and destructors. If you always wrap dynamically allocated objects in smart pointers, even when they're class members, you won't need to manage your own memory at all. See the Rule of Zero. The idea is that it's not the responsibility of your class to implement any form of ownership semantics (SRP) - that's what the smart pointers are for. Then you theoretically never have to write copy/move constructors, copy/move assignment operators or destructors, because the implicitly defined functions will generally do the appropriate thing.

提交回复
热议问题