Post by Dan EspenPost by J. ClarkePost by Dan EspenPost by Scott LurndalPost by Dan EspenPost by Jorgen Grahn...
When objects go out of range, they get freed automatically. Objects
have destructors so you can embed all your cleanup in the destructor
and it gets invoked when you destroy the object or it goes out of
range.
That's a good summary.
And the reason I said "stays in the C tradition" is that it's still
structs on the stack, or embedded in other objects, with well-defined
lifetimes.
Thanks.
Where I work we had an interesting experience with C++ new vs C malloc.
I forget the exact numbers but with malloc, if you malloc a single byte,
there's overhead but I believe it's something like 4 bytes for thousands
of 1 byte mallocs. Every new takes at least 4 (could have been 8)
additional bytes for every single new. So, this application programmer
came to me and couldn't figure out why his program converted to C++ was
running out a memory. That's when I dug through some control blocks to
figure out what was going on.
So, warning, if you are using new for lots of small memory chunks, watch
out.
The g++ default implementation of the C++ 'new' operator simply calls malloc
on linux.
malloc will allocate memory that's aligned to the default platform alignment
(generally the size of the largest native data type, so 64 or 128 bits typically),
and will allocate 64 bits just before the returned address for heap state.
#include <stdlib.h>
int main() {
char *x = new char[10];
char *y = (char *)malloc(10);
}
g++ -g -c -Wa,-alh x.C
Produces a call to _Znam for new, but a call to malloc for new.
That last line makes no sense to me. Do I need more coffee or should
one of those "new"s be something else?
Yeah, I should have just posted the generated code.
new calls _Znam
malloc calls malloc
$ c++filt _Znam
operator new[](unsigned long)
The function 'operator new[]' calls _Znwm which calls malloc.
Dump of assembler code for function _Znam:
=> 0x00007ffff7ac4370 <+0>: sub $0x8,%rsp
0x00007ffff7ac4374 <+4>: callq 0x7ffff7abdba8 <***@plt>
0x00007ffff7ac4379 <+9>: add $0x8,%rsp
0x00007ffff7ac437d <+13>: retq
0x00007ffff7ac437e <+14>: add $0x1,%rdx
0x00007ffff7ac4382 <+18>: mov %rax,%rdi
0x00007ffff7ac4385 <+21>: je 0x7ffff7ac438c <_Znam+28>
0x00007ffff7ac4387 <+23>: callq 0x7ffff7ac0458 <***@plt>
0x00007ffff7ac438c <+28>: callq 0x7ffff7abe578 <***@plt>
Dump of assembler code for function _Znwm:
=> 0x00007ffff7ac42c0 <+0>: push %rbx
0x00007ffff7ac42c1 <+1>: test %rdi,%rdi
0x00007ffff7ac42c4 <+4>: mov %rdi,%rbx
0x00007ffff7ac42c7 <+7>: mov $0x1,%eax
0x00007ffff7ac42cc <+12>: cmove %rax,%rbx
0x00007ffff7ac42d0 <+16>: mov %rbx,%rdi
0x00007ffff7ac42d3 <+19>: callq 0x7ffff7abe028 <***@plt>
0x00007ffff7ac42d8 <+24>: test %rax,%rax
0x00007ffff7ac42db <+27>: je 0x7ffff7ac42e0 <_Znwm+32>
0x00007ffff7ac42dd <+29>: pop %rbx
0x00007ffff7ac42de <+30>: retq