Difference between string literal and constexpr array of char

后端 未结 1 1128
轮回少年
轮回少年 2020-12-18 21:16

I have been wondering if there is any difference between what is being pointed by ptrToArray and ptrToLiteral in the following example:

<         


        
1条回答
  •  粉色の甜心
    2020-12-18 21:47

    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.

    0 讨论(0)
提交回复
热议问题