Why is it possible to assign a const char* to a char*?

后端 未结 5 2071
粉色の甜心
粉色の甜心 2021-01-04 03:27

I know that for example \"hello\" is of type const char*. So my questions are:

  1. How can we assign a literal string like \"hel

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 04:19

    In your example, you are not assigning, but constructing. std::string, for example, does have a std::string(const char *) constructor (actually it's more complicated, but it doesn't matter). And, similarly, char * (if it was a type rather than a pointer to a type) could have a const char * constructor, which is copying the memory.

    I don't actually know how the compiler really works here, but I think it could be similar to what I've described above: a copy of "Hello" is constructed in stack and s is initialized with this copy's address.

提交回复
热议问题