When to use “delete”?

前端 未结 5 1721
天命终不由人
天命终不由人 2020-12-06 07:36

I want to store 10 Obj object in objList, but i don\'t know when is appropriate use delete in this case. If i use delete Obj;

5条回答
  •  星月不相逢
    2020-12-06 08:15

    Well, the simple rule is that each variable constructed by new should be clean up by delete.

    However depending on your goal, you may not need write the delete yourself.

    At home, when learning the gory details of memory management, you will probably write as many delete as you write new.

    Professionals, however, never use delete in applicative code (*). delete is a code smell. It's the shortest way to memory leaks in the presence of exceptions. Professionals use RAII to deal with exceptions safely, and namely: smart pointers/smart containers.

    (*) as opposed to library code, ie someone wrote that shared_ptr class one day.

提交回复
热议问题