Click here to Skip to main content
13,454,507 members (55,053 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


26 bookmarked
Posted 29 Sep 2012

Local NEW or Automatic heap cleanup when leaving scope

, 29 Sep 2012
Rate this:
Please Sign up or sign in to vote.
Improve exception safety and reducin memory leaks
This is an old version of the currently published article.


Pointers always envied automatic cleanup that is in c++ provided only for big fat slow Static Object or their arrays stored by value.  

Manual cleanup is source of bugs. 

Automatic cleanup provided for static objects saves time lines of code and a lot and I mean really lot of bugs. Bugs by forgetting to match all allocations with deallocations. 
Bugs by memory being leaked when exception exits something some where prematurely and not all control paths contain correct number of release statements. 
Bugs by releasing objects twice or more and corrupting memory by confused condition statements.


But pretty much any program serious about performance will store objects by pointers and not by value because price for reallocation insert or sort is otherwise horible. 

So can't we have both? Performance and efficiency of pointers and safety and simplicity of static objects by automatic cleanup when leaving scope?

Reinventing Wheel 

Turns out that I am not the first one thinking along those lines and Boost template library already provides us ptr_vector.  vector of shared_ptr or shared_array.
Templates are great when everything is working. But take this example of guy having trouble sorting simple array of pointers and geting responses like

"...The IS specifies that a predicate should not assume that the dereferenced iterator yields a non-const object. Arguments should therefore be taken by reference-to-const or by value.

The IS also specifies that algorithms that take function objects as arguments are permitted to copy those function objects. So in most cases, the overloaded function call operator would be a const member function." 

So if you are like me preffering things small and simple so you know by simple look at source what is going on.
Or just don't plan to rewrite all your code to use templates stl and boost
Let's try simpler approach.  

Scopes for dynamic heap objects ?  

So how automatic cleanup for static objects work? 
It works by adding pointer of every static object within scope to internal invisible static array and when leaving calling destructors for each of them. Can we make something similar for dynamic objects?
Why not. We can have array of void pointers and store pointers to various object types in one single array.
The only issue are calling proper object specific destructors. Unfortunately as far as I know c++ doesnt allow to get destructor adresses. So the only sollution I come up so far is to use virtual destructor in all stored objects so polymorphysm selects proper one for us. 

First Primitive implementation of Scope.h 

struct Scope {
       struct Obj { virtual ~Obj() {} };
       Scope*    prev;  Obj* ptr;
       Scope() : prev(0) ,   ptr(0) {}	
      ~Scope() { delete ptr; delete prev; }

inline void * __cdecl operator new(unsigned int size,Scope& scope)
    void *ptr = (void *)malloc(size);
    if(scope.ptr) { Scope* prev=0; prev=(Scope*)calloc(sizeof(Scope),1); *prev=scope;
    scope.prev=prev; }

This very simple nothrow new overload just as proof of concept;
Also Scope is very primitive linked list kept simple on purpose. 
Beware: only objects having virtual destructor work ie no primitive types and alike.

Example code

#include <stdio.h>
#include <stdlib.h>
#include "Scope.h"   

struct A {
             A(){ printf("\n  A %x",this); }
    virtual ~A(){ printf("\n ~A %x",this); }

Scope global;

void Test() {
    Scope local; // all objects associated with scope will be deallocated with it
    for(int i=0;i<3;i++) {
        A* a=new(local) A();
    A* b=new(global) A(); 

void main() {


   A 689718   A 68b110   A 68b198   A 68b220 ~A 68b198 ~A 68b110 ~A 689718 ~A 68b220

Points of Interest 

The fact that only objects with virtual destructor can be autodeallocated is kinda sad. I hope that some way to get around this limit is found.
Also if you want to autodeallocate memory from malloc/calloc just create new type of Scope and call free instead of delete in its destructor. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ladislav Nevery
Software Developer (Senior)
Slovakia Slovakia
Past Projects:
[]Mobile network software: HLR-Inovation for (Corba)
Medical software: CorRea module for CT scanner
[]Computer Games:XboxLive/net code for Conan, Knights of the temple II, GeneTroopers, CivilWar, Soldier of fortune II
[]Computer Games:XboxLive/net code for Elveon game based on Unreal Engine 3
ESET Reasearch.
Looking for job

You may also be interested in...

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
QuestionDidn't know there is a new operator in C Pin
Stan Mihai18-Jul-13 4:41
memberStan Mihai18-Jul-13 4:41 
QuestionWhy not std::unique_ptr<T>? Pin
C++ Pirate Programmer18-Oct-12 5:46
memberC++ Pirate Programmer18-Oct-12 5:46 
AnswerRe: Why not std::unique_ptr? Pin
Ladislav Nevery18-Oct-12 16:02
memberLadislav Nevery18-Oct-12 16:02 
QuestionThanks Pin
YannAchard18-Oct-12 1:29
memberYannAchard18-Oct-12 1:29 
AnswerRe: Thanks Pin
Ladislav Nevery18-Oct-12 13:00
memberLadislav Nevery18-Oct-12 13:00 
GeneralMy vote of 2 Pin
SeattleC++15-Oct-12 9:53
memberSeattleC++15-Oct-12 9:53 
GeneralRe: My vote of 2 Pin
Ladislav Nevery16-Oct-12 9:56
memberLadislav Nevery16-Oct-12 9:56 
GeneralRe: My vote of 2 Pin
SeattleC++16-Oct-12 11:24
memberSeattleC++16-Oct-12 11:24 
GeneralRe: My vote of 2 Pin
Ladislav Nevery17-Oct-12 5:44
memberLadislav Nevery17-Oct-12 5:44 
GeneralRe: My vote of 2 Pin
SeattleC++17-Oct-12 10:29
memberSeattleC++17-Oct-12 10:29 
GeneralRe: My vote of 2 Pin
Ladislav Nevery17-Oct-12 23:06
memberLadislav Nevery17-Oct-12 23:06 
QuestionWhat's about an exception handling? Pin
konik1015-Oct-12 6:05
memberkonik1015-Oct-12 6:05 
AnswerRe: What's about an exception handling? Pin
Ladislav Nevery16-Oct-12 1:47
memberLadislav Nevery16-Oct-12 1:47 
GeneralRe: What's about an exception handling? Pin
konik1023-Oct-12 21:24
memberkonik1023-Oct-12 21:24 
GeneralRe: What's about an exception handling? Pin
Ladislav Nevery24-Oct-12 22:58
memberLadislav Nevery24-Oct-12 22:58 
GeneralRe: What's about an exception handling? Pin
konik1025-Oct-12 1:20
memberkonik1025-Oct-12 1:20 
GeneralRe: What's about an exception handling? Pin
Ladislav Nevery25-Oct-12 4:41
memberLadislav Nevery25-Oct-12 4:41 
GeneralRe: What's about an exception handling? Pin
konik1025-Oct-12 5:43
memberkonik1025-Oct-12 5:43 
GeneralRe: What's about an exception handling? Pin
Ladislav Nevery25-Oct-12 12:50
memberLadislav Nevery25-Oct-12 12:50 
QuestionException / Thread safety? Pin
Petro Protsyk8-Oct-12 1:20
memberPetro Protsyk8-Oct-12 1:20 
AnswerRe: Exception / Thread safety? Pin
Ladislav Nevery8-Oct-12 7:54
memberLadislav Nevery8-Oct-12 7:54 
GeneralMy vote of 2 Pin
Patrick Niedzielski7-Oct-12 5:38
memberPatrick Niedzielski7-Oct-12 5:38 
GeneralRe: My vote of 2 Pin
Ladislav Nevery7-Oct-12 10:26
memberLadislav Nevery7-Oct-12 10:26 
GeneralRe: My vote of 2 Pin
Patrick Niedzielski7-Oct-12 10:30
memberPatrick Niedzielski7-Oct-12 10:30 
GeneralMy vote of 5 Pin
nv33-Oct-12 22:03
membernv33-Oct-12 22:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180321.1 | Last Updated 29 Sep 2012
Article Copyright 2012 by Ladislav Nevery
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid