从操作员内部获取有关对象的RTTI信息
Getting RTTI information about object from within operator new/delete
我想在课后后得出所有内容,我不认为新的或删除的任何过载:
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;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 从操作员内部获取有关对象的RTTI信息
- 使用c++中的RTTI将对象强制转换为正确的类型
- 在没有 RTTI 的情况下对对象进行计数
- 对从外部库派生的对象使用RTTI
- 如何从指针中知道 gcc 的 c++ 对象的 RTTI 信息"this"?