std :: string get(char *)而不是(const char *)

问题描述:

std :: string.c_str()返回一个(const char *)值。我Googled,发现我可以做以下:

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

这是怎么回事? & myString [0] std :: string 类型的对象, p>

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


& myString [0] std :: string

的对象。 myString [0] 是对字符串的第一个字符的引用; & myString [0] 是指向该字符的指针。运算符优先级是这样的,它表示&(myString [0])而不是(& mystring)[0]

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

注意,以这种方式访问​​,不能保证字符串将是零终止;所以如果你在一个C型函数中使用这个函数,期望一个零终止的字符串,那么你将依赖未定义的行为。

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.