C ++字符串文字的类型 [英] Type of a C++ string literal

查看:265
本文介绍了C ++字符串文字的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我想知道C ++字符串文字的真正基础类型是什么。



根据我观察到的,我得到不同的结果。 / p>

类型测试如下:

  std :: cout ;& typeid(test)。name()< std :: endl; 

显示我 char const [5]



尝试将字符串文字指定给不兼容的类型,如下所示(查看给定的错误):

  wchar_t * s =hello; 

我得到类型const char *的值不能用于从VS12的IntelliSense中初始化一个类型为wchar_t *

$

的实体。



但我不知道如何可以 const char * ,因为VS12接受以下行:

  char * s =Hello ; 

我读过,这是在C ++ 11之前的标准中允许的,与C的兼容性,虽然修改 s 将导致未定义的行为。我假设这只是VS12尚未实现所有的C ++ 11标准,这行通常会导致错误。



读取C99标准从这里,6.4.5.5)表明它应该是一个数组:


多字节字符
序列然后用于初始化数组


所以,下面的类型是什么一个C ++字符串文字?



非常感谢您的宝贵时间。

解决方案

字符串文字的类型确实是 const char [SIZE] 其中 SIZE



有时你会看到 const char * 的字符串的长度加上空的结束符。是因为通常的数组到指针衰减。


但我不知道如何可以 const char * ,因为VS12接受了以下行:
char * s =Hello;


这是C ++ 03中的正确行为(作为通常的const正确性规则的一个例外),但是它已被弃用。符合C ++ 11标准的编译器不应接受该代码。


Out of curiosity, I'm wondering what the real underlying type of a C++ string literal is.

Depending on what I observe, I get different results.

A typeid test like the following:

std::cout << typeid("test").name() << std::endl;

shows me char const[5].

Trying to assign a string literal to an incompatible type like so (to see the given error):

wchar_t* s = "hello";

I get a value of type "const char *" cannot be used to initialize an entity of type "wchar_t *" from VS12's IntelliSense.

But I don't see how it could be const char * as the following line is accepted by VS12:

char* s = "Hello";

I have read that this was allowed in pre-C++11 standards as it was for retro-compatibility with C, although modification of s would result in Undefined Behavior. I assume that this is simply VS12 having not yet implemented all of the C++11 standard and that this line would normally result in an error.

Reading the C99 standard (from here, 6.4.5.5) suggests that it should be an array:

The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.

So, what is the type underneath a C++ string literal?

Thank you very much for your precious time.

解决方案

The type of a string literal is indeed const char[SIZE] where SIZE is the length of the string plus the null terminating character.

The fact that you're sometimes seeing const char* is because of the usual array-to-pointer decay.

But I don't see how it could be const char * as the following line is accepted by VS12: char* s = "Hello";

This was correct behaviour in C++03 (as an exception to the usual const-correctness rules) but it has been deprecated since. A C++11 compliant compiler should not accept that code.

这篇关于C ++字符串文字的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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