Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

c++ - 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:

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?
  • 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...