r*****r 发帖数: 397 | 1 I feel that I need to delete everytime after I use "new" to create a pointer.
What if I want to put the new inside a loop?For example
myobj * np;
for (int i =1;i
...
np = new myobj();
}
delete np;
will this work?Or do I have to delete np inside the loop? |
R*******r 发帖数: 104 | 2 Your program will have memory leak, delete it inside loop.
.
【在 r*****r 的大作中提到】 : I feel that I need to delete everytime after I use "new" to create a pointer. : What if I want to put the new inside a loop?For example : myobj * np; : for (int i =1;i: ... : np = new myobj(); : } : delete np; : will this work?Or do I have to delete np inside the loop?
|
r*****r 发帖数: 397 | 3 then I guess I also need to declare myobj * np inside the loop?
【在 R*******r 的大作中提到】 : Your program will have memory leak, delete it inside loop. : : .
|
m******n 发帖数: 21 | 4 It won't work. Even if you define np outside the loop.
You have to do:
myobj * np;
for (int i = 1; i < nloop; ++i)
{
...
np = new myobj();
...
delete np;
}
or you could you smart pointer:
#include
for (int i = 1; i < nloop; ++i)
{
...
std::auto_ptr np(new myboj());
(use np just like plain poiters)
}
.
【在 r*****r 的大作中提到】 : I feel that I need to delete everytime after I use "new" to create a pointer. : What if I want to put the new inside a loop?For example : myobj * np; : for (int i =1;i: ... : np = new myobj(); : } : delete np; : will this work?Or do I have to delete np inside the loop?
|
r*****r 发帖数: 397 | 5 then I guess I also need to declare myobj * np inside the loop?
【在 R*******r 的大作中提到】 : Your program will have memory leak, delete it inside loop. : : .
|
c*r 发帖数: 278 | 6 Even you declare it as a globle or static, it doesn't matter.
new abd delete must match!
outside
【在 r*****r 的大作中提到】 : then I guess I also need to declare myobj * np inside the loop?
|
N*********y 发帖数: 105 | 7 you should NOT use np in this way. Since you are using it more like a local
variable, you should allocate the memory block outside the loop.
outside
【在 r*****r 的大作中提到】 : then I guess I also need to declare myobj * np inside the loop?
|