简体   繁体   中英

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

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?

&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.

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.

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.

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';

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;

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 * .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM