字符串类的c_str()方法返回什么? [英] What does c_str() method from string class returns?

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

问题描述

我想访问由字符串类维护的数组的起始地址。

I want to access starting address of the array that is maintained by the string class.

string str="hey";
char* pointer=(char*)str.c_str();




  1. 是指向数组地址的指针(由字符串类维护)?还是字符串类会从动态内存中创建一个新数组,并将现有的字符串复制到其中并返回其地址?

  1. Is the pointer pointing to the address of the array(maintained by the string class)? or string class will create a new array from dynamic memory and copy the existing string into it and return it's address?

如果这不是正确的方法,那么如何访问由字符串类维护的数组的起始地址?

If this is not the right way, then how to access the starting address of the array that is maintained by the string class?


推荐答案

C ++ 11 标准中明确指出 .c_str()(以及更新的 .data())应返回指向内部对象的指针 std :: string 使用的缓冲区。

In C++11 standard it's explicitly stated that .c_str() (as well as newer .data()) shall return pointer to the internal buffer which is used by std::string.

获取指针后对std :: string的任何修改通过 .c_str() 可能导致说 char * 返回无效(即是-如果 std :: string 在内部必须重新分配空间)。

Any modification of the std::string after obtaining the pointer via .c_str() may result in said char * returned to became invalid (that is - if std::string internally had to reallocate the space).

在以前的C ++标准中,允许实现返回任何东西。但是,按照标准,不需要用户取消分配结果,因此我从未见过任何实现会返回新分配的任何内容。至少GNU gcc和MSVC ++的STL字符串在内部为零终止的char数组,由 c_str()返回。

In previous C++ standards implementation is allowed to return anything. But as standard do not require user to deallocate the result, I've never seen any implementation returning anything newly allocated. At least GNU gcc's and MSVC++'s STL string are internally zero-terminated char arrays, which are returned by c_str().

因此可以安全地假设(对于C ++而言,这是正常的),在任何版本的C ++中,只要实现, .c_str()都将返回内部缓冲区。

So it's safe to assume (with normal for C++ caution) that in any version of C++ in any it's implementation .c_str() will return internal buffer.

换句话说-除非您100%确信会赢,否则永远不要保留 .c_str()的值。 t将来可以随时更改大小(除非它是 const ,也就是说)。

In other words - you should never ever keep the value of the .c_str() unless you are 100% sure it's won't change it's size anytime in future (unless it's a const, that is).

PS顺便说一句,永远不要执行 char *指针=(char *)str.c_str(); 。它是 const char * ,您不应修改其内容,部分原因是上述内容-您可能最终覆盖了某些其他对象的内存损坏 std :: string 的内部状态,以防实现做一些花哨的事情,例如索引字符以更快地 .find() (新手看到了,但是嘿-这是封装!)

P.S. BTW, you should never ever do char* pointer=(char*)str.c_str();. It's const char * and you shall not modify the contents, partly because the above - you may end-up overwriting memory of some other object or corrupting internal state of std::string, in case implementation doing something fancy, like indexing characters for faster .find()(newer seen that, but hey - that's an encapsulation!)

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

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