带有返回char *函数的内存管理 [英] Memory Management with returning char* function

查看:279
本文介绍了带有返回char *函数的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,没有太多的想法,我写了一个简单的函数返回一个char *基于给定枚举值的switch语句。然而,这让我想知道我如何释放那个记忆。我做的是这样的:

Today, without much thought, I wrote a simple function return to a char* based on a switch statement of given enum values. This, however, made me wonder how I could release that memory. What I did was something like this:

char* func()
{
    char* retval = new char[20];
    // Switch blah blah - will always return some value other than NULL since default:
    return retval;
}

如果这是一个天真的问题,释放内存看到我不能删除内存后返回,显然,如果我删除它之前,我不会有一个返回值。我认为一个可行的解决方案是这样的

I apologize if this is a naive question, but what is the best way to release the memory seeing as I cannot delete the memory after the return and, obviously, if I delete it before, I won't have a returned value. What I was thinking as a viable solution was something like this

void func(char*& in)
{
    // blah blah switch make it do something
}

int main()
{
    char* val = new char[20];

    func(val);
    // Do whatever with func (normally func within a data structure with specific enum set so could run multiple times to change output)

    delete [] val;
    val = NULL;
    return 0;
}

任何人都对此有更深入的了解和/

Would anyone have anymore insight on this and/or explanation on which to use?

尊敬的,

Dennis M。

Regards,
Dennis M.

推荐答案

您可以在对中编写此类函数,例如

You could write such functions in pair, like

Xyz* CreateXyz();
void DestroyXyz(Xyz *xyz);


Abc* NewAbc();
void DeleteAbc(Abc *abc);

或者你可以将客户删除Xyz / Abc的责任转移给客户,函数也必须在使用后返回的对象上执行 delete

Or you simply can transfer the responsibilty of deleting Xyz/Abc to the clients, i.e ones who call the function must also do delete on the returned object after using it.

无论您选择什么,请在您的文档中清楚地说明所创建的对象应该如何销毁

Whatever you choose, make it clear in your documentation how the created object should be destroyed.

我更喜欢对函数,特别是如果在删除之前需要考虑很多事情!

I would prefer pair-functions, especially if there is lot of things to consider before deleting!

顺便说一下,你应该优先使用 std :: string ,而不是 char * 。尽可能多地使用STL。他们可以解决你的大多数问题!以上建议是针对STL不适合的情况!一般来说,喜欢STL!

By the way, you should prefer using std::string, instead of char*. Make use of STL as much as you can. They can solve most of your problems! The above advice is for situations where STL doesn't fit! In general, prefer STL!

这篇关于带有返回char *函数的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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