I am trying to implement operator new with parameter as global. There is no problem if new without args is overloaded, but I get followings errors when trying to compile
inline void* operator new(size_t, void* p) {
//...
return p;
}
c:\bjarne_exercise_6.cpp(14): error C2084: function ‘void *operator new(size_t,void *) throw()’ already has a body
c:\program files\microsoft visual studio 10.0\vc\include\new(55) : see previous definition of ‘new’c:\bjarne_exercise_6.cpp(40): error C2264: ‘operator new’ : error in function definition or declaration; function not called
I have just solved this, you have to declare this before you #include stdafx.h
No, not true. It compile well but still not this function is called but the version from new header file. It is so, because placement new(with 2 params) is already defined in new header. The ordinary new (with just 1, size_t parameter) is only declared there, so you can still overload it. So if you want special new with more than 1 parameter the solution suggested by @trion below is appropriate.
The C++ standard defines a placement
operator newtaking an additionalvoid*in the header file<new>.Its implementation is similar to this:
It’s commonly used to instantiate objects on already allocated memory, e.g. by STL containers which separate allocation from instantiation. So if you include any standard header depending on
<new>, the placement new will already be defined.If you want to create your own version of
operator newwith different semantics, you can use a dummy parameter to disambiguate the situation:Edit: The reason why you can redefine the ordinary
operator newbut not placement new, is that the former is by default defined by the compiler and can be overridden manually, whereas placement new is defined in a header, therefore causing a conflict with your re-definition.