有关new() T()

在看AngelScript文档的时候,讲到值对象构造函数和析构函数的注册,看到这样的内容:

void Constructor(void *memory)
{
  // Initialize the pre-allocated memory by calling the
  // object constructor with the placement-new operator
  new(memory) Object();
}

这里的new运算符有点怪哈,以前没见过,但只要不是傻子应该都能从上下文猜出含义。不过为了科学的严谨性,还是上网查了一下。这里就是不分配内存,而是直接在memory的地方进行构造。

顺便也把析构贴上。析构代码:

析构比较简单,直接调用析构即可。

void Destructor(void *memory)
{
  // Uninitialize the memory by calling the object destructor
  ((Object*)memory)->~Object();
}

反过来看为什么构造函数不是直接调用构造函数呢。我想应该还有虚函数表啊什么的一大堆乱七八糟事情要在构造函数前调用(事实上,好像有虚函数的类构造函数就是虚函数,至少分析彩虹岛的RTTI信息都是这样的)

参考文章:《new的六种重载形式》

http://dev.firnow.com/course/3_program/c++/cppjs/200827/99702.html

EDIT:用原来WP的插件插源代码指针符号总是会被变成>,下了个Source Code Formatter试试看~~

EDIT2: WLW会给Source Code Formatter的HTML代码自动换行,IE8会使换行也显示出来,要用兼容模式才能正常查看代码

Leave a Reply

Your email address will not be published. Required fields are marked *