关于使用new创建的变量范围的问题 [英] Question about scope of variables created with new

查看:50
本文介绍了关于使用new创建的变量范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个程序:


#include< iostream>

#include< conio.h>

使用命名空间std;


int * ptest();


int main()

{

int * b = ptest();

getch();


返回0;

}


int * ptest()

{

int num = 5;

int * intp = new int(num);


返回intp;

}


有什么方法可以免费在函数ptest()之外为变量

intp分配的内存?谢谢

Lets say I have a program:

#include <iostream>
#include <conio.h>
using namespace std;

int* ptest();

int main()
{
int* b = ptest();
getch();

return 0;
}

int* ptest()
{
int num = 5;
int* intp = new int(num);

return intp;
}

Is there any way to free the memory that was allocated for the variable
intp outside of the function, ptest()? Thanks

推荐答案

africamp写道:
africamp wrote:
让我说我有一个程序:

#include< iostream>
#include< conio.h>
使用命名空间std;

int * ptest();

int main()
{*> int * b = ptest();
getch();

返回0;
}

int * ptest()
{int / num = 5;
int * intp = new int(num);

返回intp ;


有没有办法释放在函数ptest()之外为变量
intp分配的内存?谢谢
Lets say I have a program:

#include <iostream>
#include <conio.h>
using namespace std;

int* ptest();

int main()
{
int* b = ptest();
getch();

return 0;
}

int* ptest()
{
int num = 5;
int* intp = new int(num);

return intp;
}

Is there any way to free the memory that was allocated for the variable
intp outside of the function, ptest()? Thanks




当然。只做:


删除b;


在main。



Of course. Just do:

delete b;

within main.


但不是那只是删除指向整数的指针而不是

整数本身?

but doesn''t that just deleter the pointer to the integer and not the
integer itself?


" africamp" < AF ****** @ gmail.com>写了...
"africamp" <af******@gmail.com> wrote...
但是这不只是删除指向整数的指针而不是
整数本身吗?
but doesn''t that just deleter the pointer to the integer and not the
integer itself?




否,''删除''销毁对象,然后释放用于该对象的内存

。指针值用于告诉''删除''

在哪里找到对象和内存。指针本身存在。


V



No, ''delete'' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the ''delete''
where to find the object and the memory. The pointer itself survives.

V


这篇关于关于使用new创建的变量范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆