Reputation: 1019
I have implemented the placement new like this:
inline void* operator new (std::size_t n, void* ptr) {return ptr;};
The environment I use has no standard library so I need placement new. The syntax for using this placement new operator should look like this:
::new (pointer) int();
For what reason do I need the size? My std::size_t is unsigned int. The reason why I do this is because there is no dynamic memory allocation available and I get all the pointers from a pool.
Upvotes: 5
Views: 2586
Reputation: 36607
I intended this to be only a comment, but following melpomene's suggestion that it is an answer ....
The C++ standard requires that all overloads of operator new()
or operator new []()
accept a std::size_t
as the first argument (and that the implementation will ensure the size of whatever is being constructed is passed via that argument).
A placement new is simply an overload of the corresponding operator new()
or operator new []()
. As such, it is required to be in that form.
The reasoning is, presumably, to allow for the possibility of any such overloaded function needing to allocate memory, in which case it would need access to size information.
There is nothing stopping your overloaded version from ignoring the size argument - which probably explains why the standard does not bother to allow overloading operator new()
or operator new[]()
without that parameter.
Upvotes: 6