问题描述
我一直想知道在 ptrToArray
和 ptrToLiteral
中指向的内容之间是否有任何区别示例:
I have been wondering if there is any difference between what is being pointed by ptrToArray
and ptrToLiteral
in the following example:
constexpr char constExprArray[] = "hello";
const char* ptrToArray = constExprArray;
const char* ptrToLiteral = "hello";
- 我理解
constExprArray
并且两个hello
文字都是编译时常数lvalue正确? - 它们在运行时在幕后是否有不同的处理方式?
- 还要了解什么?
- Is my understanding that
constExprArray
and the two"hello"
literals are all compile time constant lvalues correct? - If so, is there any difference in how they are stored in the executable file, or is it purely compiler implementation or platform specific?
- Are they treated differently at runtime behind the scenes?
- Anything else to know about?
推荐答案
字符串文字和constexpr数组几乎相同。指向它的指针是地址常量表达式。允许在常量表达式中对其元素进行左值到右值转换。它们都有静态存储持续时间。我知道的唯一的区别是,一个字符串文字可以初始化数组,而constexpr数组不能:
A string literal and a constexpr array of char are almost identical. 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 char a[] = "hello";
constexpr char b[] = a; // ill-formed
constexpr char b[] = "hello"; // ok
为了解决这个问题,你可以将数组包装在一个类型的文字类型中。我们目前正在考虑标准化这样一个包装器,它将被称为 std :: string_literal
或类似的,但现在你必须手动这样做。
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.
这篇关于字符串文字和constexpr之间的区别char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!