简体   繁体   中英

why overloaded new operator is calling constructor even I am using malloc inside overloading function?

I am trying to understand overloading new operator. I wrote the code as below.

#include <iostream>
#include <cstdlib>
#include <new>

using namespace std;

class loc
{
    int lo, la;

    public:
        loc()
        {
        }

        loc(int x, int y)
        {
            cout << "In constructor\n";
            lo = x;
            la = y;
        }

        void show()
        {
            cout << lo << " ";
            cout << la << endl;
        }

        void *operator new(size_t sz);
        void operator delete(void *p);
};

void *loc::operator new(size_t sz)
{
    cout << "in Overloaded new\n";
    void *p = malloc(sz);

    return p;
}

void loc::operator delete(void *p)
{
    cout << "in Overloaded delete\n";
    free(p);
}

int main()
{
    loc *p1 = new loc(10, 20);
    p1->show();
    delete p1;
    return 0;
}

I thought it won't call the constructor because I overloaded the new operator with malloc function call inside overloading function. But the output is as below.

in Overloaded new
In constructor
10 20
in Overloaded delete

That means constructor is getting called. How this is possible? Does this mean will malloc() call constructor?

A new expression results in two separate things happening: allocation of the memory needed by the object begin created, and initialization of the object.

The new operator , on the other hand, just handles the allocation part. When you overload the new operator with respect to a specific class, you are replacing the allocation of memory to the object.

This division of functions makes sense when you realize that not all objects are allocated on the heap. Consider the following case:

int main() {
    string someString;
    ..
}

The local variable is not dynamically allocated; new is not used; however the object still needs to be initialized so the constructor is still called. Note that you did not need to explicitly call the constructor - it is implicit in the language that an appropriate constructor will always be called to initialize an object when it is created.

When you write a 'new expression', the compiler knows to emit instructions to invoke the new operator (to allocate memory as needed) and then to call the constructor (to initialize the object). This happens whether or not you overload the new operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM