如何重载全局new操作符



在我的应用程序中,我想只保留一个给定类的给定键的对象。为此,我在类Base中重写了本地new操作符:

  void * operator new(size_t size, int k) 
  { 
      return BaseFactory::GetInstance(k);       
  }

调用BaseFactory的静态方法。此方法具有类Base的现有对象的列表。如果已经存在具有相同键的对象,则返回该对象,如果没有,则创建新对象

Base* BaseFactory::GetInstance(int k)
{
for(vector<Base*>::iterator it = bases.begin(); it < bases.end(); it++)
    if((*it)->key == k)
        return *it;
//else recognize which object to create on given key. just a simple example
    Base *l = ::new Derived(k);
bases.push_back(l);
return l;
}

它工作得很好,但我需要调用函数使用例如Base* b = new(1) Derived,虽然我想保持正常的语法,它是Base* b = new Derived(1)。我怎么能做到呢,可能吗?我猜重载全局操作符可能工作,我尝试

void *operator new (size_t size, Base& b, int key)
{
return BaseFactory::GetInstance(key);
}

但它不起作用。另外,现在我正在使用key来确定要创建哪个对象,因为key决定对象的类型(从Base派生),但也许有更好的方法。

表达式new Derived(1)中,1Derived的构造函数的参数,而不是operator new的参数。这就是语言的方式,抱歉

相关内容

最新更新