Calling delete on variable allocated on the stack

2019-01-01 09:25发布

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

For example:

   int nAmount;
   delete &nAmount;

or

class sample
{
public:
    sample();
    ~sample() { delete &nAmount;}
    int nAmount;
}

11条回答
裙下三千臣
2楼-- · 2019-01-01 09:41

You already answered the question yourself. delete must only be used for pointers optained through new. Doing anything else is plain and simple undefined behaviour.

Therefore there is really no saying what happens, anything from the code working fine through crashing to erasing your harddrive is a valid outcome of doing this. So please never do this.

查看更多
何处买醉
3楼-- · 2019-01-01 09:42

After playing a bit with g++ 4.4 in windows, I got very interesting results:

  1. calling delete on a stack variable doesn't seem to do anything. No errors throw, but I can access the variable without problems after deletion.

  2. Having a class with a method with delete this successfully deletes the object if it is allocated in the heap, but not if it is allocated in the stack (if it is in the stack, nothing happens).

查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 09:43

An angel loses its wings... You can only call delete on a pointer allocated with new, otherwise you get undefined behavior.

查看更多
若你有天会懂
5楼-- · 2019-01-01 09:51

No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new.

  • For each malloc or calloc, there should be exactly one free.
  • For each new there should be exactly one delete.
  • For each new[] there should be exactly one delete[].
  • For each stack allocation, there should be no explicit freeing or deletion. The destructor is called automatically, where applicable.

In general, you cannot mix and match any of these, e.g. no free-ing or delete[]-ing a new object. Doing so results in undefined behavior.

查看更多
浅入江南
6楼-- · 2019-01-01 09:54

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.

查看更多
登录 后发表回答