I have not programmed C++ for a while and encountered a strange behavior when toying with overloaded global operators new
and delete
.
The essence of the problem seems to be that a wrapper build around the default global new
and residing in a separate source file
nevertheless calls an operator new
overloaded in another (and separately compiled so) source file.
Why is it so, i.e. which language rules / features am I violating / misusing?
Thanks in advance, the details are below.
Project structure:
.
..
main.cpp
mem_wrappers.h
mem_wrappers.cpp
Project files contents:
main.cpp
#include "./mem_wrappers.h"
#include <iostream>
#include <cstring>
void* operator new[] (size_t sz) throw (std::bad_alloc) {
std::cout << "overloaded new()[]" << std::endl;
return default_arr_new_wrapper(sz);
}
int main() {
const unsigned num = 5;
int * i_arr = new int [num];
return 0;
}
mem_wrappers.h
#include <cstring>
void * default_arr_new_wrapper(size_t sz);
mem_wrappers.cpp
#include <new>
#include <cstring>
#include <iostream>
void * default_arr_new_wrapper(size_t sz) {
std::cout << "default_arr_new wrapper()" << std::endl;
return ::operator new[](sz);
}
Complied with g++ main.cpp mem_wrappers.cpp --ansi --pedantic -Wall when run gives endless operator new[]
to default_arr_new_wrapper
and vice versa calls resulting in the following output:
overloaded new()[]
default_arr_new_wrapper()
overloaded new()[]
default_arr_new_wrapper()
...
and, finally, in SO (the MS Visual Studio Express compiler behaves alike).
Compilers I use: gcc version 3.4.2 (mingw-special) and MS Visual Studio 2008 Version 9.0.30729.1 SP.
EDIT / UPDATE
If (as the first answers and comments suggest) the global operator new
is effectively redefined for the whole executable just by overloading it [the operator] in a single compilation unit, then:
is it that merely linking with an object file whose source overloads the global operator new
makes any application or library change its (well, lets call it so) memory allocation policy? Is thus this overload operator efficiently providing a hook for the language runtime (I mean what's with those linker symbols in the already-compiled-without-any-overloaded-new object files, is it that there can be only one new
)?
P.S. I know that malloc
and free
would do, and already tried them before posting here (worked ok), but nevertheless, what's behind this behavior (and what if I was actually to wrap the default operator new
anyway? :)) ?