0

What is the difference between these two class initializers? myClass myObject; myClass *myPointer1; myPointer1 = &myObject;

and myClass *myPointer2 = new myClass;

If the first pointer is just a pointer to a class object, where does the second pointer point to?

Codin Odin
  • 13
  • 2

1 Answers1

2

myPointer1 points to an object with automatic storage duration. As such, myPointer1 does not own the object it points to, but is simply a means of accessing that object. On the other hand, myPointer2 points to an object with dynamic storage duration, and not only is myPointer2 used to access the object, but it also needs to be used to delete the object later in order to avoid memory leaks.

One often says that myPointer1 points into "the stack" while myPointer2 points into "the heap", reflecting common implementation strategies for automatic and dynamic storage duration, respectively.

You cannot tell whether a pointer points to an object of automatic storage duration or an object of dynamic storage duration just by examining its value. You should use smart pointer objects (std::unique_ptr<myClass> and so on) to avoid memory leaks.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312