4 ms·
"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
by ebikelaw 8y ago
"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.
- marcoperaza 8y agoCould you explain?
- Tomte 8y agoplacement 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).
- vvanders 8y agoIt'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.
- ebikelaw 8y agoMoreover, 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.
- deleted 8y ago[deleted]
- imtringued 8y agoConstructors can fail via exceptions.
- Asooka 8y agoOne example: You can override operator new for a class to, instead of calling malloc, return from a static memory pool.
- gpderetta 8y agoIt 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.