从操作员内部获取有关对象的RTTI信息

Getting RTTI information about object from within operator new/delete

本文关键字:对象 RTTI 信息 操作员 内部 获取      更新时间:2023-10-16

我想在课后后得出所有内容,我不认为新的或删除的任何过载:

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
}

我没有工作,因为新和删除是静态的,但是在某种程度上有特殊的静态静态。我的问题是是否有某种方法可以获取此类信息?

as @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;
}