C++返回char*然后删除它
因此,我有这个功能:
char * func()
{
char * temp = new char[length]; // Length is defined elsewhere
/*
Do some stuff with temp
*/
return temp
}
我的问题是我不确定这是否会泄漏内存。 如果是这样,我不知道该怎么做。 我以为我可以在返回后删除它,但是我该怎么做? (还假设我不能仅仅将其删除在功能之外) 此功能是类的一部分。此功能的目的是返回类的内部值。用户将使用此功能。我发现要问用户之后删除值太多。 谢谢!
So I have this function:
char * func()
{
char * temp = new char[length]; // Length is defined elsewhere
/*
Do some stuff with temp
*/
return temp
}
My problem is I'm not sure whether or not this leaks memory.
If so, I don't know how to make it not do that.
I thought I could delete it after return, but how would I do that?
(Also assuming i can't just delete it outside the function)
This function is part of a class. This function's purpose is to return an internal value of the class. A user would use this function. i find it too much to ask that the user deletes the value afterwards.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不会泄漏内存,因为返回分配的指针,因此所有权被转移到呼叫者。如果呼叫者在删除返回的指针值之前失去了返回的指针值,则呼叫者已泄漏内存。
就是说,这是一个不好的设计。您应该避免拥有裸露的指针。相反,在这种情况下,我建议返回向量。这样,向量模板将负责释放分配的内存:
另外,如果数组表示文本,则可以考虑使用
std :: String
。This doesn't leak memory, because the pointer to the allocation is returned and thus the ownership is transferred to the caller. If the caller loses the returned pointer value before deleting it, then the caller has leaked memory.
That said, this is a bad design. You should avoid owning bare pointers. Instead, in this case I recommend returning a vector. This way the vector template will take care of releasing the allocated memory:
Alternatively, you could consider using
std::string
if the array represents text.为unique_ptr做出答案,因为它是最接近样本中所做的事情。
由于内存是由智能指针管理的,因此没有泄漏,并且是自我记录的是谁是内存的所有者:拥有unique_ptr的人
Making an answer for unique_ptr as it is the closest to what was done in your sample.
As memory is managed by smart pointer, there is no leak and is it self documented of who is the owner of the memory hunk: the one who owns the unique_ptr