std :: string get(char *)而不是(const char *) [英] std::string getting (char *) instead of (const char *)

查看:252
本文介绍了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.

这篇关于std :: string get(char *)而不是(const char *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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