2

Possible Duplicate:
What is difference between instantiating an object using new vs. without
Creating an object: with or without `new`

What is the difference between these two statements

 HttpUtil httpUtil;

and

 HttpUtil *net = new HttpUtil();

Which one is better to be used?

Community
  • 1
  • 1
Tahlil
  • 2,550
  • 4
  • 36
  • 71
  • 1
    The first allocated on the stack, the other on the heap, and it's the programmer responsibility to free it after the usage(When it's allocated on the heap). When you can without the second, prefer the first :) – Maroun Dec 18 '12 at 11:49
  • 1
    Please get a beginners book from [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – pmr Dec 18 '12 at 11:51

3 Answers3

4

The first creates an automatic variable. Memory management is automatic, allocation is faster since it's on the stack, there's no chance of a memory leak.

The second version creates a dynamic variable - you're responsible for cleaning up the memory and the allocation is slower on the heap.

Always prefer the first one. If you must use dynamic allocation (for persisting lifetime or polymorphic behavior), use smart pointers instead of raw pointers.

Luchian Grigore
  • 236,802
  • 53
  • 428
  • 594
2

The first statement creates a variable called httpUtil on the 'stack' - this means that, as soon as the function containing that line finishes, the variable goes 'out of scope' and gets released (the memory it uses becomes free to use for other stuff).

The second statement creates a variable on the 'heap' - this means that the variable will remain in memory until you call delete on it. When allocating variables on the heap you need to make sure that you always delete it at some point, otherwise you'll get memory leaks - this is where you can no longer see your *net variable, but the memory is still allocated.

benwad
  • 5,676
  • 8
  • 52
  • 89
1

First one is statically created object where you don't need to worry about its destruction. Later one is dynamically created object where you need to take care of its destruction before application terminates.

First one is preferred where you dont need to worry about memory management.

Nipun
  • 2,029
  • 4
  • 19
  • 37