0

Hopefully this isn't too basic of a question. I'm wondering if there's a difference between doing

while (1) {
    int *a = new int(1);
    // Do stuff with a
}

as opposed to

int *a;
while (1) {
    a = new int(1);
    // Do stuff with a
}

In both cases the same number of objects are dynamically allocated. But does the fact that the int keyword is used inside the loop in the first example affect the memory used?

gsgx
  • 12,020
  • 25
  • 98
  • 149

2 Answers2

4

The difference is scope.

while (1) {
    int *a = new int(1);
    // Do stuff with a

    // Don't forget to delete a.
}

// Cannot access `a` here...

Whereas:

int *a;
while (1) {
    a = new int(1);
    // Do stuff with a

    // Don't forget to delete a.
}

// Can access `a` here.

You have a memory leak in both of your examples. Prefer smart pointers!

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • Ok, I wasn't sure if the reference to a was recreated each iteration of the loop in the first example. And yea, it was implied that delete a is somewhere in // Do stuff with a. Thanks. – gsgx Apr 15 '12 at 03:26
  • I didn't think it was implied. What is it that you are actually trying to do? – johnsyweb Apr 15 '12 at 03:29
  • I was required to use a container class that only accepted dynamically allocated objects. And I was curious as to what was going on with the variable `a`. In the second example the same reference was used, but in the first I wasn't sure if new references were created in memory and the old ones would sit on the stack until the program exited. From what you're saying, the same reference is used even though I redeclare it as an int? – gsgx Apr 15 '12 at 03:32
  • There are *no* **references** in either code sample, only **pointers**. The first creates a new **pointer** on the stack with each iteration (although it's likely your compiler will optimise this). Both samples create the same number of `int`s on the heap (assuming the same number of iterations). – johnsyweb Apr 15 '12 at 03:39
4

They are essentially the same and will almost certainly be compiled identically. Even if they weren't, the fact that you're doing heap allocation is way more costly than an extra stack one.

Prefer the first though, as it has tighter scoping.

Pubby
  • 51,882
  • 13
  • 139
  • 180