简体   繁体   English

字符串文字和char的constexpr数组之间的区别

[英]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: 我一直想知道在下面的示例中, ptrToArrayptrToLiteral所指向的ptrToArray之间是否有任何区别:

constexpr char constExprArray[] = "hello";
const char* ptrToArray = constExprArray;

const char* ptrToLiteral = "hello";
  • Is my understanding that constExprArray and the two "hello" literals are all compile time constant lvalues correct? 我的理解是constExprArray和两个"hello"文字都是正确的编译时常数左值吗?
  • 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? 还有其他需要知道的吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM