Take the concept of a regular pointer. It’s a variable that points to an object in the memory. Let’s look at the downsides:
[ul]
[li] If the variable is deleted before the object is deleted, then there is nothing to keep track of the object and it is forever lost in memory. This is called a Memory Leak.[/li]
[li] Multiple objects can keep a pointer reference to a given object. This can cause an issue where one object modifies the object, and the other objects assume that it’s still valid. Say I have an object type Car. I have a class CarTracker that keeps a pointer to an instance of Car. I also have a class Highway that keeps a pointer to the same instance of car. Say we assume that CarTracker “owns” the Car object and deletes it because we got into a space-bending accident, then Highway tries to access Car without knowing it has been deleted.[/li]
[li] Conversely let’s say that nobody owns Car, and neither tracker decides to delete it. Then we run into the aforementioned Memory Leak.[/li][/ul]
SharedPtr and WeakPtr are two classes designed to handle the problem of ownership of a pointer. In fact, modern day programming practices highly recommend the use of SharedPtr and WeakPtr instead of holding raw pointers. Even outside of Urho3D, we now have std::SharedPtr and std::WeakPtr to accomplish this.
SharedPtr keeps track of the object that it is pointing to globally. If my instance of Car is tracked by both Highway and CarTracker, then the SharedPtr will contain 2 references of it.
[ul]
[li]If CarTracker or Highway removes it, then instead of the object getting deleted, only CarTracker’s reference to the object is removed and the Reference Counter is decreased to 1.[/li]
[li]If both CarTracker AND Highway remove their reference to the object, then the Reference Counter is decreased to 0. [/li]
[li]Since nothing references the object anymore, the SharedPtr class will delete the object at that point.[/li][/ul]
WeakPtr helps to solve the problem of ownership. For example, if the previously mentioned instance of Car were supposed to be deleted as soon as CarTracker removes it, then SharedPtr cannot solve this on its own.
[ul]
[li] In this case, CarTracker should continue to hold a SharedPtr since it “owns” the Car.[/li]
[li] Highway should instead hold a WeakPtr. This way if CarTracker removes the Car, the Car should be gone.[/li]
[li] If the Car is gone and Highway still references the Car, then Highway will simply get a NULL value when attempting to access the pointer. This way we safely know when we no longer have a Car to track and can take appropriate action.[/li][/ul]
Let me know if you have any more questions and I will do my best to clear things up for you