c_str()真正返回的是什么 [英] What c_str() really returns

查看:142
本文介绍了c_str()真正返回的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对成员函数string :: c_str()感到困惑。

它是否创建了一个新的char数组,复制内容然后返回初始元素的指针?或只是一个指向已经创建的数组的指针?

但是如果是这样,为什么像下面那样的代码不会破坏字符串对象?



I have a confusion with the member function string::c_str().
Does it create a new char array, copies the contents then returns the pointer of the initial element ? or just a pointer to the already created array ?
But if so, why a code like the one below won't destroy the string object?

string s = "Hi Sam";
const char *c = s.c_str();
delete c;





谢谢,山姆。



Thanks, Sam.

推荐答案

这是真的是一个问题,你应该解决自己bei谷歌搜索回答



解释意味着它返回指向对象内部字符串的指针。所以它不是一个新的对象或内存块。



使用调试器的详细视图来查看对象的内部内容。
This is really a question you should solver yourself bei googling for the answer.

Explained means it, that it returns the pointer to the inner string of the object. So it is NOT a new object or memory block.

Use the detail view of your debugger to see the inner guts of objects.


您提供的代码可以在C ++程序中执行任何操作 - 其行为未定义。



那么是什么原因使它未定义?在这种情况下有两件事:



- 你正在删除一些尚未被新分配的东西

- 你要删除一个数组使用错误的删除形式



所以除非一个类的合同告诉你要删除一些东西,否则不要!
The code you presented could do just about anything in a C++ program - its behaviour is undefined.

So what makes it undefined? Two things in this case:

- you're deleting something that hasn't been allocated by new
- You're deleting an array using the wrong form of delete

So unless the contract for a class tells you to delete something, DON'T!


这篇关于c_str()真正返回的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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