In the following:
int main()
{
new int; // Works
int* pmem = 0;
new (pmem) int;// Doesn't recognize new keyword/operator/function???
}
It won't recognise 'new' in this case without including the < iostream > header. Why is that? Why doesn't 'new' require a header but placement new does? If 'new' requires a function to be defined then why does 'int* a = new int;' work? Since it's not defined anywhere, I assumed it's part of the language. However 'new (&int) int;' 'placement new' isn't part of the language?
Visual Studio gives error:
'operator new': no overloaded function takes 3 arguments
Placement new isn't just for "no-op" allocation. It's a general term for providing extra arguments to new
beyond the object size. A standard example would be std::nothrow
.
Since we are providing arguments, the compiler has to do overload resolution to choose an appropriate operator new
function. And that means that overloads must be declared beforehand. The most basic overload is implicitly declared (in a way), while void* operator new(std::size_t, void* ptr) noexcept
(the standard library function that does this "allocation") is not. So we must include the header (<new>
*) for overload resolution.
That was the design choice made 30 years ago. It could have been done by another built-in, but since placing objects into pre-allcoated raw storage is deemed a pretty advanced feature (as opposed to simple dynamic allocation), adding a library dependency probably didn't seem like much of a hindrance.
* - You saw <iostream>
affecting the behavior because it probably includes <new>
either directly or indirectly. It's permissible, but not required behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With