understanding pointers c++
When i write this code:
Animal *p;
Animal b;
p = &b;
In the first line when I am creating a point开发者_开发问答er. Does a new object of Animal is created or only when you write the second line?
Thanks.
When you declare a pointer [and the declaration is a definition], space is only allocated for a pointer, there is no Animal
object created.
If you don't initialize the pointer you can't use it in any way except to point it at a valid Animal
object or to assign it the special "null pointer value" to indicate that the pointer doesn't point at a valid object. You can't even test whether it's actually pointing at a valid Animal
object at all.
It is always advisable to initialize pointers either to null or to a valid object as soon as you create them, so I would recommend either:
Animal* p = 0; // or = NULL
Animal u;
p = &u;
or better:
Animal u;
Animal* p = &u;
In the first line, a pointer is created but it doesn't point to anything yet. In the second line you create an actual Animal
object.
Animal *p;
creates a pointer, Animal b;
creates an animal.
A new object is created on the stack when that method is created and goes away when the method returns. It is going to crash your application if you return that value from the method and try to use it since the stack memory will have been deallocated as a part of returning from the method.
// create a pointer to an animal object and initialize it to NULL
//Animal* p; // Bad! Do not do this
Animal* pA = NULL; // Much better
Animal a; // creates an Animal object on the stack (local scope)
Animal pA = &a; // sets pA to point to the location of a
Now when a
goes out of scope, pA
will still point to that memory location. If you try to access it, bad things can (and will) happen.
精彩评论