Simplifying Concepts

Essence of Life is in Simplicity

Pointers

Smart Pointers and Naked Pointers

C++ supports pointers there comes the concept of smart and naked pointer.Apart from C++ pointers are also used in game programming to dynamically allocate and deallocate memory and for pointing game world objects.

Naked Pointers

  • These are basically pointers to the object and are declared using new operator.
  • They are often referred to dumb or raw pointers.
  • The objects pointed by these pointers are declared on the heap region of memory.
  • Also it is necessary that objects are referenced by atleast one other object.
  • Otherwise, this can lead to memory leak.
  • Because in absence of additional referencing object it is not possible to free the resources allocated to object.
  • This memory leak can lead to application crashes.
  • This situation is more possible in case of Large Application programming.

This could be better understood by an example, lets dive into an example of ship.

Imagine a ship object that owns everything on the ship. When the ship sinks, everything else is destroyed along with it. If you use naked pointers to create these relationships you have to remember who owns who. This can be a confusing or even impossible task. You’ll find that using naked pointers will quickly paint you into a corner.

It is common for an object on the heap to be referred multiple times by other objects in the code. So there comes the need for using additional objects to refer the existing object. A Example of this is a game object like a clock. A pointer to the clock will exist in the game object, in collision system, animation system, and even in the sound system. If you use naked pointers you must remember which objects implicitly own other objects. An object that owns other objects controls their existence.

Smart pointers

  • On the other hand, Smart Pointers hold additional information along with the address of the distant object.
  • This information could be regarding count of references, record permanence or temporary ownership, or information to perform other useful tasks.
  • In a sense an object controlled by a smart pointer “knows” about every reference to itself.
  • The horrible nest of naked pointers evaporates, leaving a simple and foolproof mechanism for handling your dynamic objects.

Hey all stay tuned to conceptsimplified.com. We at ConceptSimplified are eager to hear from you. Please give comments or feedback. Waiting for the opportunity to improve and cater to your needs.

Post a comment

error: Content is protected !!