简体   繁体   中英

overload operator new(), why constructor is called twice?

I can`t understand some problems when learning new/delete overload. Questions:

  1. Why new is called before constructor,destructor before delete?
  2. Why constructor is called twice when using ::new ?

I've appended the code here:


#include<iostream>

using namespace std;

class MyClass
{
public:
    MyClass() { 
        cout << "My Class is Constructed !" << endl; 

    }

    ~MyClass() { cout << "My Class is Deleted ! " << endl; }

     static void *operator new(size_t Size)
    {
        cout << "new call" << endl;
        MyClass *p = ::new MyClass;
        return p;
     }
     static void operator delete(void *p)
     {
         cout << "delete call" << endl;
         ::delete p;
     }

};
int main()
{
    MyClass  *p = new MyClass;
    delete p;
    cin.get();
    return 0;
}

output:
new call
My Class is Constructed !
My Class is Constructed !
My Class is Deleted !
delete call

The reason why this is happening is because when you allocate something with new , the allocation and construction happens in two phases. The first is the actual allocation and the second is construction via placement new.

The overload you have provided is just for allocating memory (hence the size_t parameter), but instead you called new on the class which will do both steps from above. You should only allocate the memory in that function. So change your function to be

static void *operator new(size_t size)
{
   return ::operator new(size);
}

And you will see the class being constructed only once.

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