初始化使用类的malloc [英] Initializing a class using malloc
问题描述
我正在使用C ++作为中间语言AVR玩具语言,问题是AVR-GCC没有新的实现。我所有的对象从Object类里面有虚方法推导出当我创建使用说从指令使用malloc一个浮点对象,</ P>
<一个href=\"http://stackoverflow.com/questions/1031301/can-i-implement-the-factory-method-pattern-in-c-without-using-new/1031375#1031375\">Can我实现C ++ Factory Method模式,而无需使用新的?
当我将它转换为对象,以四周,回传给了一个浮动我的程序崩溃,在回答评论说,这是由于虚函数表不正确初始化,所以我怎么能不使用新创建一个C ++对象妥善有虚表的设置?
看来,新
作为一种语言结构的支持,但是运营商新
code强调它和它的实际分配未实现。
这应该是pretty容易解决,通过提供自己的实现运营商新的
在源$ C $ C:
在该公司包含在任何文件中需要一些头文件新
的#include&LT;&stdlib.h中GT;void *的new操作符(为size_t大小);
void运算符删除(无效* PTR);
在一个单一的cpp文件。
void *的new操作符(为size_t大小)
{
返回的malloc(大小);
}无效的operator delete(void *的PTR)
{
免费(PTR);
}
来源:上avrfreaks.net,这也该帖子包含有关你可能想/需要你自己去实现一些其他的东西的信息。
I am working on a toy language for avr using C++ as the intermediate language, Problem is avr-gcc does not have new implemented. All my object derive from the class Object which has virtual methods when I create say a float object with malloc using instructions from,
Can I implement the Factory Method pattern in C++ without using new?
as soon as I cast it to an Object to pass around and back to a Float my program crashes, comments in the answer says that this is due to vtable not initializing properly, so how can i create a c++ object without using new and have the vtable setup properly?
It appears that new
as a language construct is supported, but the operator new
code that underlies it and does the actual allocation isn't implemented.
It should be pretty easy to fix that by providing your own implementation for operator new
in your source code:
In some header file that's included in any file needing new
#include <stdlib.h>
void * operator new(size_t size);
void operator delete(void * ptr);
In a single cpp file.
void * operator new(size_t size)
{
return malloc(size);
}
void operator delete(void * ptr)
{
free(ptr);
}
Source: this post on avrfreaks.net, which also contains information about some other stuff you may want/need to implement on your own.
这篇关于初始化使用类的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!