使用 new 运算符返回指针。删除该放在哪里?
我对 C++ 相当陌生。
所以我了解到 new 分配内存并返回我的数据类型的指针。但是我可以在函数中使用它并返回指针吗?如果是这样那么我应该将删除运算符放在哪里?
下面的代码合法吗?
int *makeArray(int size)
{
int *result = new int[size];
delete[] result;
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... */
return 0;
}
它正在编译和工作,但从逻辑上讲它没有任何意义,因为我删除了我的数组。
所以我尝试了以下操作:
int *makeArray(int size)
{
int *result = new int[size];
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... do some stuff with pointer */
delete[] pointer;
return 0;
}
这安全还是会导致内存泄漏?有没有更好的方法返回指针?
我尝试了这两个版本,它们正在编译和工作,但我确信至少其中一个(如果不是两个)都不安全。
Im fairly new to C++.
So I learned that new
allocates memory and returns a pointer of my datatype. But can I use this in a function and return the pointer? If so then where should I place the delete operator?
Is the following code legal?
int *makeArray(int size)
{
int *result = new int[size];
delete[] result;
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... */
return 0;
}
It is compiling and working but logically it makes no sense because I deleted my array.
So I tried the following:
int *makeArray(int size)
{
int *result = new int[size];
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... do some stuff with pointer */
delete[] pointer;
return 0;
}
Is this safe or does it cause a memory leak? Is there a better way of returning the pointer?
I tried both versions and they are compiling and working but I'm sure at least one of them if not both are unsafe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
绝对不!这是未定义行为,因为您返回了一个已删除的指针。使用删除运算符后,您告诉操作系统它可以释放内存并将其用于任何它想要的用途。读取或写入它是非常危险的(程序崩溃、蓝屏、银河系毁灭)
是的,这是使用 new 和 delete 运算符的正确方法。您使用
new
,这样您的数据即使超出范围也保留在内存中。无论如何,这不是最安全的代码,因为对于每个new
都必须有一个delete
或delete[]
你不能混合它们。是的。它称为智能指针。在 C++ 中,程序员根本不应该使用 new,而应该使用智能指针。有一个 C++ 社区编码指南可以避免这些调用 指南 R11
Definitely not! This is Undefined behavior because you return a deleted pointer. After using the delete operator you're telling your OS that it can release the memory and use it for whatever it wants. Reading or writing to it is very dangerous (Program crashing, Bluescreen, Destruction of the milky way)
Yes this is the correct way of using the
new
and delete operator. You usenew
so your data stays in memory even if it gets out of scope. Anyway it's not the safest code because for everynew
there has to be adelete
ordelete[]
you can not mix them.YES. It's called Smart Pointer. In C++ programmers shouldn't use
new
but smart pointer at all. There is a C++ community Coding Guideline to avoid these calls Guideline R11