我可以获取在重载的新运算符中使用新运算符的对象类型吗?
Can i get the type of object for which new operator is used inside the overloaded new operator?
好吧,我有这个函数重载:
static bool returnNull;
void* operator new(const std::size_t size, const std::nothrow_t&) noexcept
{
void* address{ nullptr };
if (!returnNull)
{
address = operator new(size);
}
return address;
}
我想做一些类似的东西:
void* operator new(const std::size_t size, const std::nothrow_t&) noexcept
{
if (typeObject == AnimalClass)
return nullptr;
void* address{ nullptr };
if (!returnNull)
{
address = operator new(size);
}
return address;
}
因此,我需要此功能来对具有许多新调用的构建器进行单元测试,因此我想根据应定位的类使特定分配失败
你的代码做什么可以通过new
类 AnimalClass
的运算符重载来实现:
class AnimalClass
{
public:
#ifdef UNIT_TEST
void* operator new(size_t)
{
return nullptr;
}
#endif
};
可以使用预处理器指令#ifdef
将代码保留在测试之外。在标头包含之前定义UNIT_TEST
。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 运算符重载 += 添加新对象
- 如何用 2 个对象过度引导运算符
- C++内联运算符重载中,请参阅当前对象
- 使用运算符"="在C++中用值初始化对象
- C++运算符重载做双 * 对象
- 如何在自定义对象的<<运算符中添加自定义前缀
- 尝试重载输出运算符时,我无法遍历对象向量
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 在之后仍需要使用源对象时调用父移动分配运算符
- 错误:三元运算符无法在对象中正常工作"cout"
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 无法使用迭代器查找类对象。(二进制 '==': 'userInfo' 不定义此运算符)
- 重载加法运算符(使用函数向对象添加字符串)
- 临时对象上的运算符重载
- 如何使用运算符+重载函数正确返回对象?
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 重载运算符 [] 用于从对象数组中给出特定索引