在函数内部做 new 和指向它的指针 return 可以吗?
Is it Okay to do new inside a function and return the pointer to it?
下面的代码片段是否正确,或者它有什么问题?
据我所知,用 new
分配的内存不会被擦除,除非有一个 delete
所以返回它的指针应该没问题?
// Example program
#include <iostream>
#include <string>
int* a()
{
int* aa = new int(1);
*aa = 44;
return aa;
}
int main()
{
int *aa = a();
printf("%d ", *aa);
}
不太理想。谁负责删除指针?您没有在示例中的任何地方删除它,因此存在内存泄漏。
通常,如果您需要动态分配,那么您应该 return 一个智能指针。也就是说,通常最好避免不必要的动态分配。可能永远不需要动态分配单个 int
.
下面的代码片段是否正确,或者它有什么问题?
据我所知,用 new
分配的内存不会被擦除,除非有一个 delete
所以返回它的指针应该没问题?
// Example program
#include <iostream>
#include <string>
int* a()
{
int* aa = new int(1);
*aa = 44;
return aa;
}
int main()
{
int *aa = a();
printf("%d ", *aa);
}
不太理想。谁负责删除指针?您没有在示例中的任何地方删除它,因此存在内存泄漏。
通常,如果您需要动态分配,那么您应该 return 一个智能指针。也就是说,通常最好避免不必要的动态分配。可能永远不需要动态分配单个 int
.