Question

I am trying to overload global new and delete. So I have created a separate lib to keep both however when I try to use them i am seeing that my mehotds do not get called. Someone could tell me why and how I could fix, please? Here is my code:

file my_operator.cpp
#include <cstdlib>
#include <cstdio>

void* operator new(size_t size)
{
    puts("constructing");
    void* p = malloc(size);
    return p;

}

void operator delete(void *p) throw()
{
    puts("deleting");
    free(p);
}

file myclass.h
class clase
{
private:
    int x;
public:
    clase(int i):x(i){}
    inline int getX(){return x;}
};

main.cpp
#include "myclass.h"

int main()
{
    int k = 5;
    int ret = 0;
    clase* c = new clase(k);
    delete c;
    return ret;
}

what I have tried so far:
running this:

g++ -c my_operator.cpp -o my_operator.o && g++ main.cpp my_operator.o -o main

then launching ./main --> it works, my operators get called

however
running this:

g++ -c my_operator.cpp -o my_operator.o ld -o my_operator.so my_operator.o -shared to create the .lib file and then
g++ main

and finally running ./a.out does not work properly, my operators do not get called
Any clue?
Thanks in advance!

Was it helpful?

Solution

Your commands don't link your main with my_operator.so. You need something like the following:

g++ -Wall -Wextra -c -fPIC -o my_operator.o my_operator.cpp
g++ -shared -o libmy_operator.so my_operator.o
g++ -Wall -Wextra -c -o main.o main.cpp
g++ -o main main.o -lmy_operator
./main

OTHER TIPS

Your main.cpp does not know that you overloaded the operators. Put your overload operators in the header file.

Usefull links on this matter: http://en.cppreference.com/w/cpp/memory/new/operator_new http://www.cprogramming.com/tutorial/operator_new.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top