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

2019-05-26 09:38发布

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?

7条回答
我命由我不由天
2楼-- · 2019-05-26 10:19

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楼-- · 2019-05-26 10:22

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-05-26 10:23

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;
查看更多
SAY GOODBYE
5楼-- · 2019-05-26 10:23

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.

查看更多
孤傲高冷的网名
6楼-- · 2019-05-26 10:35

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楼-- · 2019-05-26 10:41

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';
查看更多
登录 后发表回答