Calling delete on variable allocated on the stack

前端 未结 11 2093
遇见更好的自我
遇见更好的自我 2020-11-22 14:35

Ignoring programming style and design, is it \"safe\" to call delete on a variable allocated on the stack?

For example:

   int nAmount;
   delete &am         


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 15:09

    Well, let's try it:

    jeremy@jeremy-desktop:~$ echo 'main() { int a; delete &a; }' > test.cpp
    jeremy@jeremy-desktop:~$ g++ -o test test.cpp
    jeremy@jeremy-desktop:~$ ./test
    Segmentation fault
    

    So apparently it is not safe at all.

提交回复
热议问题