Link to home
Start Free TrialLog in
Avatar of Nusrat Nuriyev
Nusrat NuriyevFlag for Azerbaijan

asked on

29. Can we define new operation?

Can we define new operation?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nusrat Nuriyev

ASKER

Is this example more or less complete?

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
class MyClass
{
public:
        MyClass(){ cout << "MyClass::MyClass() is called" << endl;}
        void doSmth() { cout << "MyClass::doSmth() is called" << endl;}
        void* operator new(size_t);
        void operator delete(void*);
};

void* MyClass::operator new(size_t size)
{
    void *storage = malloc(size);


    cout << "Placement new operator is called" << endl;

    if(NULL == storage) {
            throw "allocation fail : no free memory";
    }
    return storage;
}

void MyClass::operator delete(void *obj)
{
    cout << "Delete operator is called" << endl;
    free(obj);

    obj = NULL;
}

int main()
{

    MyClass *mc = new MyClass;

    mc->doSmth();

    delete mc;

}

Open in new window



>>> There is also a so-called 'placement new' that allows you to create an object on a certain memory area that you can choose.

How we can create an object on a certain memory area?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thank you, will  review that a bit later
Yes, I have checked obj=NULL  does not affect the original pointer.
When I tried to change to void** , it started to blame:
new_del.cpp:13:30: error: ‘operator delete’ takes type ‘void*’ as first parameter
   void operator delete(void**);

Open in new window

Yes, we may overload the new and delete, but are those operator's prototypes are "carved in stone"?
int buffer[256]; // providing 'sizeof(MyClass)' only would work with gcc/g++

Open in new window


I don't get this comment. PLease, explain.