我可以获取在重载的新运算符中使用新运算符的对象类型吗?

Can i get the type of object for which new operator is used inside the overloaded new operator?

本文关键字:运算符 对象 类型 获取 我可以 重载      更新时间:2023-10-16

好吧,我有这个函数重载:

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;
}
因此,

我需要此功能来对具有许多新调用的构建器进行单元测试,因此我想根据应定位的类使特定分配失败

你的代码做什么可以通过newAnimalClass 的运算符重载来实现:

class AnimalClass
{
public:
   #ifdef UNIT_TEST
   void* operator new(size_t)
   {
      return nullptr;
   }
   #endif
};

可以使用预处理器指令#ifdef将代码保留在测试之外。在标头包含之前定义UNIT_TEST