What's the purpose of using braces (i.e. {}) for a single-line if or loop?

前端 未结 23 1370
独厮守ぢ
独厮守ぢ 2020-11-28 00:33

I\'m reading some lecture notes of my C++ lecturer and he wrote the following:

  1. Use Indentation // OK
  2. Never rely on operator preced
23条回答
  •  清酒与你
    2020-11-28 01:35

    It is best to set the pointer to NULL when you have finished with it.

    Here is an example why:

    Class A does the following:

    1. Allocates a block of memory
    2. Then some time later, it delete this block of memory but does not set the pointer to NULL

    Class B does the following

    1. Allocates memory (and in this instance it happens to be given the same memory block that was deleted by class A.)

    At this point both Class A and Class B have pointers pointing to the same memory block, as far as Class A is concerned this block of memory does not exists because it is finished with it.

    Consider the following problem:

    What if there was a logic error in Class A which resulted in it writing to memory that now belongs to Class B?

    In this particular instance, you will not get an bad access exception error because the memory address is legal, all the while class A is now effectively corrupting class B data.

    Class B may eventually crash if it encounters unexpected values and when it does crash, chances are, you will spend quite a long time hunting this bug in class B when the problem is in class A.

    If you had set the deleted memory pointer to NULL, you would have gotten an exception error as soon as any logic errors in Class A tried to write to NULL pointer.

    If you are worried about the logic error with double delete when pointers are NULL for the second time, then add assert for this.

    Also: If you are going to down vote, please explain.

提交回复
热议问题