Game Development Community

Not so safe TorqueSafePtr

by AIDan · in Torque X 3D · 06/02/2009 (2:42 pm) · 2 replies

The problem is that the object is cleared. This can cause problems when using different threads.

For example:

if(handle.Initialized)
handle.Object.DoSomething();

The handle could become invalid after checking the Initialized property.

As the object is cleared, handle.Object will return null.

The following would be much safer:

public sealed class Handle<T>
	{
		protected bool _isValid;
		protected T _object;

		public bool IsValid
		{
			get { return _isValid; }

			set
			{
				// we can only invalidate handles
				if(!value)
					_isValid= false;
			}
		}

		public T Object
		{
			get { return _object; }
		}

		public Handle(T obj)
		{
			_object= obj;
			_isValid= obj !=null;
		}
	}

The advantage is that even after the object became invalid, Object still returns a valid object so the currently running process can continue. When it is done or the next time it checks IsValid, the process can bail out.

#1
06/02/2009 (4:29 pm)
I have to disagree with your approach here. Multi-threading is a beast of a topic, and if your value has the possiblity of changing after you access Initialised, then you need to use locking. Returning a different object just to keep the process running is going to cause you problems in the long run, guaranteed.
#2
06/02/2009 (4:59 pm)
The problem is that this:

if(handle.Initialized)
handle.Object.DoSomething();

Is not thread safe, no matter how you slice it.

It should be more like:

MyObject x = handle.Object;
if (x != null)
{
    x.doSomething();
}
else
{
    // Handle the case where the object is no longer valid
}

I think you're missing the point of Handle<>.