[英]Difference between string literal and constexpr array of char
I have been wondering if there is any difference between what is being pointed by ptrToArray
and ptrToLiteral
in the following example: 我一直想知道在下面的示例中, ptrToArray
和ptrToLiteral
所指向的ptrToArray
之间是否有任何区别:
constexpr char constExprArray[] = "hello";
const char* ptrToArray = constExprArray;
const char* ptrToLiteral = "hello";
constExprArray
and the two "hello"
literals are all compile time constant lvalues correct? 我的理解是constExprArray
和两个"hello"
文字都是正确的编译时常数左值吗? A string literal and a constexpr array of char are almost identical. 字符串文字和char的constexpr数组几乎相同。 A pointer to either is an address constant expression. 指向其中一个的指针是地址常量表达式。 An lvalue-to-rvalue conversion is permitted on their elements in a constant expression. 在常量表达式中允许在元素上进行左值到右值转换。 They both have static storage duration. 它们都有静态存储期限。 The only difference that I know of is that a string literal can initialize an array whereas a constexpr array cannot: 我知道的唯一区别是字符串文字可以初始化数组,而constexpr数组不能:
constexpr char a[] = "hello";
constexpr char b[] = a; // ill-formed
constexpr char b[] = "hello"; // ok
To get around this you can wrap the array in a class of literal type. 为了解决这个问题,您可以将数组包装在文字类型的类中。 We are currently looking at standardizing such a wrapper that will be called std::string_literal
or similar, but for now you will have to do this by hand. 我们目前正在考虑将这样的包装器标准化,该包装器将被称为std::string_literal
或类似的包装器,但是现在您必须手动执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.