c++ - 如何重载全局新运算符

标签 c++ operator-overloading new-operator

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

  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 来确定要创建哪个对象,哪个是 OK,因为 key 确定对象的类型(从 Base 派生),但也许有更好的方法。

此外,我对任何其他设计模式持开放态度。

最佳答案

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

关于c++ - 如何重载全局新运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817185/

相关文章:

c++ - 正则表达式 : group for every found item (PCRE)

c++ - 重载新运算符和继承

c++ - 为什么 new int (*)[3] 是错误的?

c++ - C++ 中多重集的自定义 [] 访问

c++ - 在智能指针上调用成员函数指针

c++ 带参数的新类数组

c++ - 重复排列的排名和取消排名

c++ - 错误: expected `,' or `...' before '.' token

c++ - 在 C/C++ 中在本地时间和 GMT/UTC 之间转换

c++ - 是否可以通过运算符重载按索引分配用户定义的数组? - C++