让我们说我想在下面的课后得到所有东西,我不假设任何进一步的新的重载或删除:
class Object
{
public:
static map<std::string, unsigned int> typeDeltaMap;
void* operator new(size_t size)
{
void* p = ::new char[size];
const std::string type = typeid(this).name(); //compile error
cout << "new type=" << type << endl;
++typeDeltaMap[type];
}
void operator delete(void* p)
{
::delete(p);
const std::string type = typeid(this).name(); //compile error
cout << "delete type=" << type << endl;
--typeDeltaMap[type];
}
};
我想最终得到像这样的东西
class A : public Object
{
public:
virtual ~A(){}
};
class B : public Object
{
public:
virtual ~B(){}
};
int main()
{
A* a = new A();//prints new type=A
B* b = new B();//prints new type=B
delete a;//prints delete type=A
delete b;//prints delete type=B
}
我没有工作,因为新的和删除是静态的,但有一些特殊的静态,因为它们同时是虚拟的。 我的问题是,是否有某种方法可以获得这些信息?
答案 0 :(得分:1)
正如@Someprogrammerdude建议我使用CRTP来满足我的需求
template<typename T>
class Object
{
public:
;
void* operator new(size_t size)
{
const std::string type = typeid(T).name();
cout << "new type=" << type << endl;
void* p = ::new char[size];
return p;
}
void operator delete(void* p)
{
const std::string type = typeid(T).name();
cout << "delete type=" << type << endl;
::delete(p);
}
};
class A : public Object<A>
{
public:
virtual ~A(){}
};
class B : public Object<B>
{
public:
virtual ~B(){}
};
int main()
{
A* a = new A();
B* b = new B();
delete a;
delete b;
}