Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"In C++ creating variables using the new operator always means that you have a heap variable."

It's hard to make accurate statements about C++ :-) This is not one. Perhaps it would be more correct to say "In C++ a |new| expression is used to construct an object whose lifetime is not necessarily bound to the scope in which it is created" or something like that. It is definitely not true that an object created with |new| is allocated on a heap. It can be placed on the stack, or any place, or maybe not even allocate.



It can even go away. The compiler can remove the allocation if the pointer doesn't escape and its lifetime is constrained by block scope.

C++ Compilers historically haven't been willing to perform the optimization for various reasons, but things are changing recently.


Could you explain?


One example: You can override operator new for a class to, instead of calling malloc, return from a static memory pool.


placement new lets you choose where to construct an object.

It‘s somewhat arcane, though. Few application programmers even know about it (although their C++ books all dutifully mention it, usually without more than a single sentence).


It's not that arcane, we used it all the time for pooling, particle systems, in-place loading, etc. Super handy but also like most things in C++, dangerous if you don't know what you're doing.


Moreover, the outcome of a new expression isn't strongly defined. Your class may override operator new for any class-type T, and you may also override global operator new, and you may do whatever it is that you like when you do so. Same for delete.


Constructors can fail via exceptions.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: