5

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

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

typeid 测试如下:

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

给我看char const[5]

尝试将字符串文字分配给这样的不兼容类型(查看给定的错误):

wchar_t* s = "hello";

a value of type "const char *" cannot be used to initialize an entity of type "wchar_t *"从 VS12 的 IntelliSense 获得。

但我不明白它会如何,const char *因为 VS12 接受了以下行:

char* s = "Hello";

我已经读过这在 C++11 之前的标准中是允许的,因为它是为了与 C 进行追溯兼容,尽管修改s会导致未定义的行为。我假设这只是 VS12 尚未实现所有 C++11 标准,并且这一行通常会导致错误。

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

然后使用多字节字符序列来初始化一个静态存储持续时间和长度刚好足以包含该序列的数组。

那么,C++ 字符串文字下面的类型是什么?

非常感谢您宝贵的时间。

4

3 回答 3

8

字符串文字的类型确实const char[SIZE]SIZE字符串的长度加上空终止字符。

您有时看到的事实const char*是由于通常的数组到指针衰减。

但我不明白它会如何,const char *因为 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.

于 2013-08-24T21:18:56.810 回答
5

The type of a string literal is char const[N] where N is the number of characters including the terminating null character. Although this type does not convert to char*, the C++ standard includes a clause allowing assignments of string literal to char*. This clause was added to support compatibility especially for C code which didn't have const back then.

The relevant clause for the type in the standard is 2.14.5 [lex.string] paragraph 8:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

于 2013-08-24T21:19:17.010 回答
-1

First off, the type of a C++ string literal is an array of n const char. Secondly, if you want to initialise a wchar_t with a string literal you have to code:

wchar_t* s = L"hello"
于 2013-08-24T21:21:27.817 回答