std::string getting (char *) instead of (const char *)

一世执手 提交于 2019-12-08 00:59:18

问题


std::string.c_str() returns a (const char *) value. I Googled and found that I can do the following:

std::string myString = "Hello World";
char *buf = &myString[0];

How is this possible? &myString[0] is an object of type std::string, so how can this work?


回答1:


&myString[0] is a object of type std::string

No it isn't. myString[0] is a reference to the first character of the string; &myString[0] is a pointer to that character. The operator precedence is such that it means &(myString[0]) and not (&mystring)[0].

Beware that, accessed this way, there's no guarantee that the string will be zero-terminated; so if you use this in a C-style function that expects a zero-terminated string, then you'll be relying on undefined behaviour.




回答2:


There are const and non-const overloads of std::string::operator[]( size_type pos ), and the non-const version returns a char&, so you can do things like

std::string s("Hello");
s[0] = 'Y';

Note that, since s[0] returns char&, then &s[0] is the address of element s[0]. You can assign that address to a char*. It is up to you not to misuse this pointer.




回答3:


It has to do with operator precedence. The [] operator has higher precedence than the address-of operator &, so the address-of operator works on the character reference returned by the strings operator[] function.




回答4:


The operator [] (std::string::char& operator[] (size_t pos)) overloaded returns a reference to the character at the index. You are taking the address of such character reference which is fine.

So, myString[0] return type is not std::string but char&.

There is no reason to do it. You can directly do -

myString[0] = 'h';



回答5:


The std::string methods c_str() and operator[] are two diferent methods, which return two different types.

The method c_str() does indeed return a const char*.

const char* c_str() const;

However, the method operator[] returns instead a reference to a char. When you take the address of it, you get the address of a char.

       char& operator[] (size_t pos);
 const char& operator[] (size_t pos) const;



回答6:


You are wrong. &myString[0] is not of type std::string, it is of type char *.

The [] operator has higher precedence and operator[] returns a reference to char, and its address (the & operator) is of type char *.




回答7:


The std::string type has an operator[] that allows indexing each one of the characters in the string. The expression myString[0] is a (modifiable) reference to the first character of the string. If you take the address of that you will get a pointer to the first character in the array.



来源:https://stackoverflow.com/questions/17813074/stdstring-getting-char-instead-of-const-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!