[lug] new operator in C++

D. Stimits stimits at idcomm.com
Sat Apr 27 17:01:27 MDT 2002


Tkil wrote:
> 
> >>>>> "Tkil" == tkil  <tkil at scrye.com> writes:
> 
> Tkil> i think i got it right this time.  the bit i cited in the
> Tkil> previous message had to do with static initialization; both
> Tkil> automatic and dynamic initializations have the above rules (that
> Tkil> is, "if there are no initializers, then it's indeterminate").
> 
> to wit:
> 
> | #include <iostream>
> | using std::cout;
> | using std::endl;
> |
> | int main( int argc, char * argv [] )
> | {
> |     for (int i = 0; i < 100 ; ++i)
> |     {
> |         int * pi = new int;
> |         ++(*pi);
> |         cout << *pi << endl;
> |         delete pi;
> |     }
> |     return 0;
> | }
> 
> gives this output:
> 
> | $ ./test-new
> | 1
> | 1075981201
> | [...]
> | 1075981201
> | 1075981201
> | 1075981201
> | $
> 
> which surprises me a little -- i had hoped for something more
> consistent -- but shows that you do not get the zero initialization
> that you asked for.

delete was called after each new; thus the same memory slot was likely
to be reused each time. Had you done all the new operators in a row on
separate variables, your results would not have been the same in all
likelihood. Or if you had done other memory operations possibly the slot
being used would have been different.

D. Stimits, stimits at idcomm.com



More information about the LUG mailing list