Is it good practice to NULL a pointer after deleting it?

后端 未结 18 1070
猫巷女王i
猫巷女王i 2020-11-22 11:28

I\'ll start out by saying, use smart pointers and you\'ll never have to worry about this.

What are the problems with the following code?

<         


        
18条回答
  •  [愿得一人]
    2020-11-22 11:59

    As others have said, delete ptr; ptr = 0; is not going to cause demons to fly out of your nose. However, it does encourage the usage of ptr as a flag of sorts. The code becomes littered with delete and setting the pointer to NULL. The next step is to scatter if (arg == NULL) return; through your code to protect against the accidental usage of a NULL pointer. The problem occurs once the checks against NULL become your primary means of checking for the state of an object or program.

    I'm sure that there is a code smell about using a pointer as a flag somewhere but I haven't found one.

提交回复
热议问题