this is the first time I ask a question. I’m a foreigner, so it’s a little bit hard to explain my question. Maybe my title is wrong too… Let’s see the code:
Suppose I have defined a class:
class Test
{
public:
Test();
};
int main()
{
Test *pointer = new Test(); //what's the difference between these two ways,
Test test; //if the two ways are the same, which one is better under what
pointer = &test; //circumstance?
}
I hope that you guys can understand what I’m saying and help me.
Test test;will create an object on the stack. It’s local to the functionmain, and will be automatically de-allocated whenmainexits. Use this when you only need to use an object in the current block.Test *pointer = new Test();will create an object on the heap, with a lifetime that isn’t limited to the block in which it is declared. When you declare an object this way – usingnew– then at some point you’ll need to calldeleteon the object or you’ll leak memory, so you assume the additional burden of handling the memory management. Use this when you need to create an object that needs to stick around, i.e. in other parts of your code, past the current function.Given these points, the following code has a problem:
When you assign to
pointerthe reference totest, you lose the pointer to the object that you’ve allocated, and leaked memory. Furthermore, if you do this in a context where you might usepointerelsewhere, e.g. in a function that returns a reference to aTestobject, it will point to a memory address that isn’t valid after the function exits.