首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符重载"new“C++

运算符重载"new“C++
EN

Stack Overflow用户
提问于 2016-04-10 09:21:27
回答 2查看 229关注 0票数 0

我在类Base中使用了这个操作符重载:

代码语言:javascript
复制
void* operator new(std::size_t sz1) {
//Se llama a la funcion de xMemoryManager
// std::printf("global op new called, size = %zu\n",sz);
cout<<"operador new"<<endl;

}

但是我从基类继承到派生类,并且我在派生类中有以下代码:

代码语言:javascript
复制
xPointer<Pruebas> *xPruebas;
xPruebas=new xPointer<Pruebas>;
xPointer<Pruebas> *xPruebas1;
xPruebas1=new xPointer<Pruebas>;

在这几行中,我需要使用基本操作符new,而不是Base类的重载操作符。

我怎么能做到这一点?

EN

回答 2

Stack Overflow用户

发布于 2016-04-10 09:25:32

为派生类编写operator new,并在其中调用::operator new

票数 1
EN

Stack Overflow用户

发布于 2016-04-10 09:46:04

您需要在派生类中重写operator new函数。这里有两个我能想到的策略。下面的程序展示了如何使用它们。

代码语言:javascript
复制
#include <iostream>
#include <cstdint>
#include <cstdlib>
#include <new>

struct Base
{
   void* operator new(std::size_t sz)
   {
      return malloc(sz);
   }
};

struct Derived1 : Base
{
   // Simple override.
   void* operator new(std::size_t sz)
   {
      return ::operator new(sz);
   }
};

struct Derived2 : Base
{
   // Can be used as placement new.
   void* operator new(std::size_t sz, void* p)
   {
      return p;
   }
};

int main()
{
   // Use operator new in the basic form.
   Derived1* ptr1 = new Derived1;
   std::cout << ptr1 << std::endl;

   // Use operator new in the placement new form.
   // Allocate memory for the object first using global operator new.
   // Then call the placement new.
   void* p = ::operator new(sizeof(Derived2));
   Derived2* ptr2 = new (p) Derived2;
   std::cout << ptr2 << std::endl;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36524669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档