其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
关于Placement operator new [].

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

今天在社区看到一个问题,在查找资料的过程中以及各位的回复中学了不少东西。记录下来。

原文:http://community.csdn.net/Expert/topic/3393/3393098.xml?temp=.7317163

?

在C++标准中,对于placement operator new []有如下的说明:

placement operator new[] needs implementation-defined amount of additional storage to save a size of array.

也就是说,申请的原始内存需要比sizeof(ELEMENT)*n多sizeof(int)字节来存储这个数组的大小。

示例程序(摘自问题,感谢作者)

#include
#include
using namespace std;
class Integer
{
private:
?int datum;
public:
?Integer(int ival = 0)
?{
??datum = ival;
?}

?Integer(Integer const& rhs)
?{
??datum = rhs.datum;
?}
?
?Integer& operator = (Integer const& rhs)
?{
??datum = rhs.datum;
??return *this;
?}

?~Integer()
?{
???? cout << "~Integer" << endl;
?}

?operator int () const
?{
??return datum;
?}
};

int main()
{
?int const ELEMENT_COUNT = 8;
?unsigned char *buffer = new unsigned char [ELEMENT_COUNT * sizeof(Integer)+sizeof(int)];//这里申请原始内存的时候需要多申请sizeof(int)个字节
?Integer *data = new (buffer) Integer[ELEMENT_COUNT];//此时data所需要的长度比ELEMENT_COUNT * sizeof(Integer)的长度要大
?for (int i = 0; i < ELEMENT_COUNT; i++)
?{
??data[i].~Integer();//placement new的用法,需要在释放原始内存之前调用对象的析构函数
?}
?delete [] buffer;//这样删除原始内存才不会有问题,否则程序会Crash.
?system("pause");
?return 0;
}

相关连接:http://gcc.gnu.org/ml/gcc/1999-07n/msg00602.html

一个类似的问题以及解决。




相关文章

相关软件