what should i use with a c++ class, with or without "new"?
When should i use the pointer and when not? Whats the better Way? Must i delete the cat object of the pointer at the end of the programm?
Example:
cat piki;
piki.miao();
cat *piki2 = new cat();
piki2->miao();
The piki
object will be autodeleted when the current scope is closed.
piki2
must be explicitly deleted.
delete piki2;
Whenever possible try to avoid creating the object using new
(ie on heap) as you would have to do memory management yourself (or at least you need to use smart pointers). If you allocate the object on stack (ie cat piki;
) the memory allocated for the cat
object is automatically released when the piki
goes out of scope. This doesn't happen with piki2
, you need to explictly do delete piki2;
to release memory.
Creating an ojbect with or without a new depends on where you are using the object. An object of your class can be created without a new if you are using it within a function, or a block so that the destructor automatically gets called once your object is out of scope.
If you want your object to be used in multiple methods or you want to return the object from a function, then you need to create the object using new, and also make sure you delete it properly.
链接地址: http://www.djcxy.com/p/82484.html