在函数块中使用 new 运算符时,是否存在于堆或堆栈中?
Live on heap or stack when use new operator within a function block?
例如:
void Func()
{
int* i = new int; // the simplest case
vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here
vector<int*>* vPointer = new vector<int*>;
}
void main()
{
Func();
}
所以,如果我为函数中的局部变量分配动态内存(通过使用 new 运算符),
- 它们是在堆上还是在栈上?
- 当程序退出函数时,它们是还在堆上晃来晃去还是作为函数变量被销毁了?
- 我可以在非指针类型上使用 new 运算符吗?稍后如何删除(或return返回分配的堆内存)?
谢谢!
int i = 3;
这会在堆栈上创建一个 int
类型的对象。 (C++ 标准使用术语 "automatic storage",我通常坚持正确使用正式术语,但 "stack" 和 "heap" 已深深嵌入编程词汇中,因此 "stack" 和 "heap" 作为技术术语就好了)。
int *ip = 0;
这会在堆栈上创建一个 int*
类型的对象。 ip
持有空指针。
int *ip = new int;
这会在堆栈上创建一个 int*
类型的对象,就像上一个一样。它持有一个指向堆上内存的指针(参见前面的括号;正式术语是 "free store")。您知道内存在堆上,因为那是 operator new
所做的。
当您使用完堆内存后,您必须释放它:
delete ip;
如果不删除它和创建它的函数 returns,保存指针的局部变量 (ip
) 就会消失。内存已分配但尚未释放,因此除非您将指针复制到其他地方,否则您无法获得分配的内存。这叫做 "memory leak".
例如:
void Func()
{
int* i = new int; // the simplest case
vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here
vector<int*>* vPointer = new vector<int*>;
}
void main()
{
Func();
}
所以,如果我为函数中的局部变量分配动态内存(通过使用 new 运算符),
- 它们是在堆上还是在栈上?
- 当程序退出函数时,它们是还在堆上晃来晃去还是作为函数变量被销毁了?
- 我可以在非指针类型上使用 new 运算符吗?稍后如何删除(或return返回分配的堆内存)?
谢谢!
int i = 3;
这会在堆栈上创建一个 int
类型的对象。 (C++ 标准使用术语 "automatic storage",我通常坚持正确使用正式术语,但 "stack" 和 "heap" 已深深嵌入编程词汇中,因此 "stack" 和 "heap" 作为技术术语就好了)。
int *ip = 0;
这会在堆栈上创建一个 int*
类型的对象。 ip
持有空指针。
int *ip = new int;
这会在堆栈上创建一个 int*
类型的对象,就像上一个一样。它持有一个指向堆上内存的指针(参见前面的括号;正式术语是 "free store")。您知道内存在堆上,因为那是 operator new
所做的。
当您使用完堆内存后,您必须释放它:
delete ip;
如果不删除它和创建它的函数 returns,保存指针的局部变量 (ip
) 就会消失。内存已分配但尚未释放,因此除非您将指针复制到其他地方,否则您无法获得分配的内存。这叫做 "memory leak".