Solved

29. Can we define new operation?

Posted on 2015-01-24
6
48 Views
Last Modified: 2015-03-17
Can we define new operation?
0
Comment
Question by:Nusrat Nuriyev
  • 4
  • 2
6 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 40568270
If you are referring to overload the 'new' operator - yes, that can be done, as well as 'delete'. Both have to be member overloads, see http://www.cprogramming.com/tutorial/operator_new.html ("Customized Allocators with Operator New and Operator Delete").

The scoop would be to

class MyClass
{
public:
        void* operator new(size_t);
        void operator delete(void*);
};

void* MyClass::operator new(size_t size)
{
    void *storage = malloc(size);
    if(NULL == storage) {
            throw "allocation fail : no free memory";
    }
}

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.
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40568442
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?
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 500 total points
ID: 40568544
Hm, first of all, sorry again, I apparently missed toprovide an example for overloading 'delete()' in the above, that would be

void MyClass::operator delete(void* p)
{
    free(p)
}

Open in new window


>> Is this example more or less complete?

It is pretty much complete, yet the line
obj = NULL;

Open in new window


in your 'delete()'  implementation is superfluous - the operator is passed a pointer by value, setting that to NULL has no effect since it is not reflected in the calling code. But anyway, the idea is good.

OK, so now further on:

>> How we can create an object on a certain memory area?

Full explanation: http://en.wikipedia.org/wiki/Placement_syntax

The gist:

#include <iostream>

class MyClass {
   
   public:

    // Placement new operator
    void* operator new (size_t sz, void* v) {
        std::cout << "Placement new called" << std::endl;
        return v;
    }

    ~MyClass() {
        // Cleanup
    }
};

int main()
{
    // Create a buffer to store the object
    int buffer[256]; // providing 'sizeof(MyClass)' only would work with gcc/g++
    std::cout << "Starting address of my buffer = " << &buffer << std::endl;

    // Create the object. Use placement new
    MyClass* obj = new (buffer) MyClass();
    std::cout << "Location of my object = " << obj <<std:: endl;

    // Don't delete object created with placement delete
    // Call the destructor explicitly
    obj->~MyClass();
}

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Nusrat Nuriyev
ID: 40606135
thank you, will  review that a bit later
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40670676
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"?
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40670802
int buffer[256]; // providing 'sizeof(MyClass)' only would work with gcc/g++

Open in new window


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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now