2 Replies Latest reply on Nov 4, 2007 6:33 AM by asincero

    Will this get garbage collected?

    asincero
      say I have the following:

      public class MyClass
      {
      private var _mySocket:Socket = null;

      public function MyClass()
      {
      _mySocket = new Socket();
      _mySocket.addEventListener(Event.CONNECT, _onSocketConnect);
      }

      private function _onSocketConnect(event:Event):void
      {
      // handle socket connect
      }
      }

      and a user of MyClass goes and does something like:

      var obj:MyClass = new MyClass();
      ...
      obj = null;

      Would the MyClass instance be garbage collected? Or will it linger on since the Socket instance owned by the MyClass object is holding a reference to the MyClass object?

      My guess is no it won't be. What's the real answer?

      Thanks.
        • 1. Re: Will this get garbage collected?
          atta707 Level 2
          No. It won't. You'll going to have to remove the listener as well before you set it to null.

          see removeEventListener() for for info.

          ATTA
          • 2. Re: Will this get garbage collected?
            asincero Level 1
            quote:

            Originally posted by: atta707
            No. It won't. You'll going to have to remove the listener as well before you set it to null.

            see removeEventListener() for for info.

            ATTA


            Thanks for confirming my suspicion. However, I suppose I could specify true for the useWeakReference parameter of the addEventListener() method too, no?

            What are the disadvantages to setting this parameter to true? There doesn't seem to be any and in fact would be a very good idea to always use true because forgetting about event listeners could easily lead to subtle memory related bugs.