Why delete can perform on pointers to const while free cannot?

前端 未结 4 903
鱼传尺愫
鱼传尺愫 2021-02-14 06:22

I\'ve just noticed that the pointers passed to delete can be const qualified while those passed to free cannot. That is really a surprise

4条回答
  •  孤街浪徒
    2021-02-14 06:48

    The const modifier applied to a pointer means that the object pointed to will not be modified.

    However, delete takes the object permanently out of circulation. No one need care what happens to it after it is deleted. Hence for all we know, deletion might modify the object or it might not. Why does it matter? Any attempt to read or write the object's contents would be undefined behaviour.

    On the other hand, when you're implementing your own delete, you will likely need to modify the dying object. Hence the need for the pointer to be non-const.

提交回复
热议问题