I am really cofused about overloading global operator new
in c++,In this situation,i can understand it as overload
:
#include <iostream>
using namespace std;
void *operator new( size_t n, const string &pat ) {
char *p = static_cast<char *>(::operator new( n ));
const char *pattern = pat.c_str();
if( !pattern || !pattern[0] )
pattern = "\0"; // note: two null chars
const char *f = pattern;
for( int i = 0; i < n; ++i ) {
if( !*f )
f = pattern;
p[i] = *f++;
}
cout<<"overload!"<<endl;
return p;
}
int main() {
string fill( "<garbage>" );
string *string1 = new string( "Hello" ); // standard version
string *string2 =
new (fill) string( "World!" ); // overloaded version,why??? because fill will be the second parameter
//and the parameter list is different from standard versions in new.h
cout<<string1<<" "<<string2<<endl;
return 0;
}
In this codeblock,I write an overloaded version of operator new
,it uses the standard version ::operator new()
,then I located thie location of the standard version:
//from new.h
void* operator new(std::size_t) _GLIBCXX_THROW (std::bad_alloc)
__attribute__((__externally_visible__));
The only parameter's type in the standard version is size_t
,then I "overload" this standard version:
#include <iostream>
using namespace std;
//overload1
void *operator new( size_t n, const string &pat ) {
char *p = static_cast<char *>(::operator new( n ));
const char *pattern = pat.c_str();
if( !pattern || !pattern[0] )
pattern = "\0"; // note: two null chars
const char *f = pattern;
for( int i = 0; i < n; ++i ) {
if( !*f )
f = pattern;
p[i] = *f++;
}
cout<<"overload1"<<endl;
return p;
}
//overload2
void* operator new(size_t n){//note:the same parameter as the standard version,why???
cout<<"overload2"<<endl;
return malloc(n);
}
int main() {
string fill( "<garbage>" );
string *string1 = new string( "Hello" ); // overloaded version:2
string *string2 =
new (fill) string( "World!" ); // overloaded version:2 and 1
cout<<string1<<" "<<string2<<endl;
return 0;
}
This time,in my overload1
version ,i called the overload2
version but not the standard version,but the parameter list of these two versions(overload2
and standard version
) are exactly the same!This is contrary to what I learned about overloading,I can understand this as replacement because in new.h
,there is such a annotate:
These are replaceable signatures: - normal single new and delete (no arguments, throw bad_alloc on error) - normal array new and delete (same) - nothrow single new and delete (take a nothrow argument, return NULL on error) - nothrow array new and delete (same) Placement new and delete signatures (take a memory address argument, does nothing) may not be replaced by a user's program.
So,Is the standard version replaced by my overload2
version?Or it is just be overloaded(really confused me),should i stop claiming that such behavior as "overload"?But it seems like everyone calls it as "overload operator new
"