you can define T (that is a class),defined two constructor and one for destructor.but you use new T for obtianning this class.if you want to rebuild constructor to other constructor without new memory for that operation,you can use replacement new operation,that can solve this probelem.
/*************************************************************************
> File Name: t.cc
> Author: perrynzhou
> Mail: perrynzhou@gmail.com
> Created Time: Fri 18 Aug 2017 06:33:20 PM AKDT
************************************************************************/
#include <cassert>
#include <iostream>
using namespace std;
class T {
public:
T()
: m_data(0)
{
cout << "default.ctor.this =" << this << ", m_data =" << m_data << endl;
}
T(int _data)
: m_data(_data)
{
cout << "ctor.this =" << this << ", m_data=" << m_data << endl;
}
~T() { cout << "dtor.this =" << this << ", m_data=" << m_data << endl; }
private:
int m_data;
};
int main(void)
{
int size = 4;
T* tes = new (std::nothrow) T[size];
assert(tes != NULL);
cout << "new T[" << size << "] addr=" << tes << endl;
T* tmp = tes;
cout << "tmp addr=" << tmp << endl;
for (int i = i; i < size; i++) {
new (tmp++) T(i + 1);
}
delete[] tes;
return 0;
}
replacement new can be converted to this:
// statment
new(temp++)T(i)
//gcc complier can convert as follow:
T *tes;
try {
void *mem = operator new(sizeof(T),temp);
tes = static_cast<T*>(mem);
tes->T::T(i);
} cache(std::bad_alloc){}
//operator new
void *opertor new(size_t,void *alloc)
{
return alloc;
}
T *obj = new T ---> {
T t= (T *)operator new(sizeof(T)); -->{ malloc(sizeof(T);}
new(T) T();
}
delete obj ---> {
obj->~T();
opertor delete(obj); --->{free(obj);
}
running this program,you can show some as follow: