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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…