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

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

问题描述

我正在嵌入式环境(Arduino / AVR ATMega328)工作,并希望在C ++中实现Factory Method模式。但是,我使用的编译器(avr-gcc)不支持新的关键字。有没有使用实现此模式的方法?

解决方案

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

  void * operator new(size_t size)
{
返回一些分配的内存足够大以容纳大小字节
}

您将需要要定义一个删除:

  void operator delete(void * memory)
{
释放记忆
}

唯一要添加的是内存管理,分配和释放记忆块这可以简单地进行,小心不要破坏任何现有的分配的内存(代码,静态/全局数据,堆栈)。您应该定义两个符号 - 一个用于开始可用内存,另一个用于可用内存的结尾。您可以在此区域动态分配和释放任何内存块。您将需要自己管理此记忆。


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?

解决方案

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
}

and you'll need to define a delete as well:

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 ++中实现Factory Method模式,而不使用新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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