avatar
new and delete in c++# Programming - 葵花宝典
C*d
1
各位,有谁有工业废水课件吗?是否可以分享下?小弟想学习学习!
avatar
r*r
2
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?
avatar
R*r
3
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?

avatar
r*r
4
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.
:
: .

avatar
m*n
5
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?

avatar
r*r
6
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.
:
: .

avatar
c*r
7
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?
avatar
N*y
8
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?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。