我可以在C ++中实现工厂方法模式而不使用新的? [英] Can I implement the Factory Method pattern in C++ without using new?

查看:243
本文介绍了我可以在C ++中实现工厂方法模式而不使用新的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在嵌入式环境(Arduino / AVR ATMega328)中工作,想要在C ++中实现Factory Method模式。但是,我使用的编译器(avr-gcc)不支持 new 关键字。是否有一种实现此模式的方法,而不使用 new

I'm working in an embedded environment (Arduino/AVR ATMega328) and want to implement the Factory Method pattern in C++. However, the compiler I'm using (avr-gcc) doesn't support the new keyword. Is there a way of implementing this pattern without using new?

推荐答案

由于AVR编译器基于gcc编译器,因此很可能支持new关键字。你得到的错误是什么。我猜这是一个链接/编译器错误沿未定义的函数,即运算符new。新操作符和操作符new之间有区别,第一个用于创建对象,后者用于为对象分配内存。新操作符对正在创建的对象类型调用operator new,然后初始化对象的v表并调用对象的构造函数。 阅读此常见问题,表示运算符new未在标准库。这很容易解决,只需定义一个:

Since the AVR compiler is based on the gcc compiler, it is very likely to support the new keyword. What exactly is the error you're getting. I'm guessing it's a link/compiler error along the lines of an undefined function, namely, operator new. There is a difference between the new operator and operator new, the first is used to create objects and the latter is used to allocate memory for objects. The new operator calls operator new for the type of object being created, then initialises the object's v-table and calls the object's constructors. Reading this FAQ it says that operator new is not defined in the standard libraries. This is easy to fix, just define one:

void *operator new (size_t size)
{
  return some allocated memory big enough to hold size bytes
}

定义一个删除:

void operator delete (void *memory)
{
   free the memory
}

唯一需要添加的是内存管理,分配和释放块的内存。这可以轻而易举地做,小心不要破坏任何现有的分配的内存(代码,静态/全局数据,堆栈)。您应该定义两个符号 - 一个用于空闲内存的开始,一个用于空闲内存的结束。您可以动态分配和释放此区域中的任何内存块。您需要自己管理此内存。

The only thing to add is the memory management, the allocation and freeing of blocks of memory. This can be done trivially, being careful not to clobber any existing allocated memory (the code, static / global data, the stack). You should have two symbols defined - one for the start of free memory and one for the end of the free memory. You can dynamically allocate and free any chunk of memory in this region. You will need to manage this memory yourself.

这篇关于我可以在C ++中实现工厂方法模式而不使用新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆