Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C

new(local) for safer and simpler code with no need for smart-pointer template wrappers

Rate me:
Please Sign up or sign in to vote.
4.65/5 (20 votes)
25 Oct 2012CPOL8 min read 92.6K   387   26  
reduce bugs and memory leaks by using new(local)
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "Scope.h"   

TScope global; // this one is threadsafe and deallocates all associated objects on program exit no matter 
               // what exception or error in program happens

struct A : Scope::Obj{  // to support autocleanup functionality just derive from Scope::Obj
       A(){ printf("\n  A %x",this); }  // so Scope knows which destructor to call
      ~A(){ printf("\n ~A %x",this); }
};

void Test() {
    Scope local; // all objects associated with scope will be deallocated by leaving procedure
    A* array[3]={0};
    for(int i=0;i<3;i++) {
        array[i]=new(local) A();
    }
    char* text=strdup(global,"this will get deallocated on program exit"); //associate with global scope
    A* a=new(global) A();  // this will get destructor called on progam exit
}

void main() {
    Test();
}  

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


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

Comments and Discussions