(Why) does an empty string have an address?

前端 未结 7 1520
执笔经年
执笔经年 2021-02-19 14:19

I guessed no, but this output of something like this shows it does

string s=\"\";
cout<<&s;

what is the point of having empty string

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 14:35

    Following your logic, int i; would also not allocate any memory space, since you are not assigning any value to it. But how is it possible then, that this subsequent operation i = 10; works after that?

    When you declare a variable, you are actually allocating memory space of a certain size (depending on the variable's type) to store something. If you want to use this space right way or not is up to you, but the declaration of the variable is what triggers memory allocation for it.

    Some coding practices say you shouldn't declare a variable until the moment you need to use it.

提交回复
热议问题