unnecessary dynamic memory allocation

The idea of this thread is to serve as a reference to link when spotting a T *foo = new T; or similar code snip.

It may also include some misconceptions that propitiate the use of such aberration (like the ignorance on initialization list, java background, declaring a function instead of an object)


delete new T
Last edited on
Why not write an article?
Bjarne Stroustrup wrote:
Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient.

ugly:
Gadget *p = new Gadget(n);
[sarcasm] c++ is so stupid that you need to tell it twice what you want [/sarcasm]

error prone:
1
2
3
4
5
6
7
8
void foo(int n, int x){
   Gadget *p = new Gadget(n);
   //...
   if(x<100) throw std::run_time_error("weird"); //leak
   if(x<100) return; //leak
   //...
   delete p; //may as well forget this
}


inefficient:
1
2
3
4
5
6
7
void foo(int n, int x){
   unique_ptr<Gadget> p = new Gadget(n); //managing that pointer
   //...
   if(x<100) throw std::run_time_error("weird"); //no leak
   if(x<100) return; //no leak
   //...
}
- one extra indirection
- cache misses
- dynamic allocation is expensive


Gadget p(n); //yay
Last edited on
> Why not write an article?
because this way I can have the beautiful feedback of the community.

And better than feedback, they could contribute too (as if I'm qualified at all)
Registered users can post here. Sign in or register to post.