Set pointers to nil after release?

前端 未结 4 718
臣服心动
臣服心动 2021-01-01 20:09

After releasing objects is it best to set the pointers to nil? Thats what I have been doing, just wanted to ask if its necessary, good practice or overkill?

         


        
相关标签:
4条回答
  • 2021-01-01 20:14

    It's considered good practice. If you set your pointers to nil after releasing them, then in case you misuse your variable at a later point of execution, you'll get a proper error.

    0 讨论(0)
  • 2021-01-01 20:15

    Depends on the scope of the variable that holds the pointer. I always set pointers to nil if they continue to exist within the scope, just in case I'm calling the variable again somewhere else. Otherwise, there's a risk that I would access a memory location that contained an object which is now released.

    But if the variable goes out of scope, then it won't be used either, thus assigning nil to it is a bit overkill. Still, it is a good practice to just assign nil just in case someone else decides to add code to your code and accidently uses the variable again within it's scope but after it was freed.

    0 讨论(0)
  • 2021-01-01 20:16

    At times this can be crucial, as I just found out. I use a camera in my game which keeps a pointer to a generic target. If you return to the main menu from a level then it clears the level from memory but keeps the camera and game layers.

    -(void) dealloc {
        [target release];
        target = nil;
        [super dealloc];
    }
    

    Since the camera will exist longer than the target, it's best to set target to nil, otherwise when the level loads again and you set a new target:

    -(void) setTarget:(CCNode *)aTarget {
        [target release];
        target = [aTarget retain];
        [self update:0];
    }
    

    It will crash on that release if the target is junk and not nil. Sending a message to nil is fine, but not to some arbitrary junk memory. That gives me a EXC_BAD_ACCESS.

    0 讨论(0)
  • 2021-01-01 20:17

    Usually when programming in C/C++ I set it to null. Why? Because even if you free the memory being pointed, the pointer still holds the address of that freed memory. It can cause a serious access violation problems in code like this:

    if(myPointer != null)
    {
       doSomething(myPointer);
    }
    

    If you had set your pointer to null, this will never happen

    0 讨论(0)
提交回复
热议问题