检查文字 [英] checking for literals

查看:57
本文介绍了检查文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



假设我正在尝试这样的事情:



  void  func( char  *& foo)
{
char * bar = new char [ 1000 ]; // 在其他地方分配更多空间
/ / 一些东西
if (foo!= null) delete [] foo; // 清理,如果有什么东西
foo = bar;
}





也就是说,代码使得foo指向其他地方(可能当前位置太小)。在这样做时,它会删除foo的当前位置,作为良好内存管理的一部分。如果用户传递使用new分配的char *,这很好。但如果他们做了类似

 char * string =text; 
func(string);





然后删除操作将失败:不能删除字符串文字。我该如何解决这个问题?有没有办法检查字符串文字?我希望我的代码能够支持他们。我相信在字符串文字的情况下正确的行为是跳过delete语句,因为文字是在内部处理的(......对吗?)。但这仍然留下了如何检测foo是否指向文字的问题。



思考?

解决方案

最好的解决方案是,如果你根本不删除它;因为简单来说你的编译器不会告诉你这是什么类型的指针(你使用什么样的编译器?)



你最好根据需要删除你的foo变量在调用函数之后,在函数外部。盲目删除函数不是一个好主意



但如果你想删除里面的变量,那么最好在函数参数列表中添加一个标志

使用一个简单的规则:创建者破坏。其他一切都是不可靠和不可移植的。



-SA


使用 std :: string 相反,避免出现问题。



内存将由课程组成,如果你不这样做,它将有助于制作一个可靠的程序完全理解内存分配的工作原理。


Hi all,

Suppose I''m trying to do something like this:

void func(char*& foo)
{
     char* bar = new char[1000]; //allocating more space somewhere else
     //some stuff
     if (foo != null) delete [] foo; //clean up, if there's something here
     foo = bar;
}



That is, the code makes foo point someplace else (maybe the current location is too small). In doing that, it deletes foo''s current location, as a part of good memory management. This is fine, if the user passes a char* allocated using new. But if they do something like

char* string = "text";
func(string);



then the delete operation will fail: string literals can''t be deleted. How do I work around this? Is there a way to check for string literals? I''d love for my code to be able to support them. I believe the correct behavior in the case of a string literal is to just skip the delete statement, since literals are handled internally (...right?). But that still leaves the question of how to detect whether or not foo points to a literal.

Thoughts?

解决方案

The best solution would be if you don''t delete this at all; because in simple word your compiler wont tell you what kind of pointer is this(by the way what compiler are you using?)

you better delete your foo variable as required outside the function, after you call the function. Its not a very good idea deleting function blindly

but if you want do delete the variable inside anyway, then you better add a flag in the function parameter list


Use a simple rule: a creator destroys. Everything else is unreliable and unportable.

—SA


Uses std::string instead and avoid problems.

Memory will be manegd by the class and it will help a lot to make a reliable program particulary if you don''t fully understand how memory allocation works.


这篇关于检查文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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