最近看到一段代码,如下:Buffers *pBuffers = 0;
int lSize, i, iListIndex;
void *pMalloc;// Calculate the buffer size taking into acoount the system
// buffer overhead and then make sure the buffers always
// start on a word boundry.sizeIn = 16;
lSize = sizeIn;
lSize += (lSize % sizeof(int));
iListIndex = 0;
pMalloc = malloc(sizeIn + sizeof(class Buffers));
pBuffers = new (pMalloc) Buffers (iListIndex);其中Buffers是一个类,没有父类。有一个构造函数Buffers(int iListID),这些都还明白。
但是最后一句new后边的(pMalloc)是怎么出来的就不明白了,有这样的语法吗?
源程序很大,可以在vc中编译执行。可是我没有见过new还能这样用的,请高手详解~~~
int lSize, i, iListIndex;
void *pMalloc;// Calculate the buffer size taking into acoount the system
// buffer overhead and then make sure the buffers always
// start on a word boundry.sizeIn = 16;
lSize = sizeIn;
lSize += (lSize % sizeof(int));
iListIndex = 0;
pMalloc = malloc(sizeIn + sizeof(class Buffers));
pBuffers = new (pMalloc) Buffers (iListIndex);其中Buffers是一个类,没有父类。有一个构造函数Buffers(int iListID),这些都还明白。
但是最后一句new后边的(pMalloc)是怎么出来的就不明白了,有这样的语法吗?
源程序很大,可以在vc中编译执行。可是我没有见过new还能这样用的,请高手详解~~~
pBuffers = new (pMalloc) Buffers (iListIndex);
===
运行后pMalloc,pBuffers在数值上是相同的,只是类型不一样。pMalloc是VOID* ,而pBuffers是Buffers* 。使用的时候要注意能够保证pMalloc指向的存储器足够大到能装下Buffers。
to:laiyiling(陌生人 求职中)
我用bounds checker检测,总是说这段代码有memory leak。是不是误报?
这样允许你自己分配内存构造对象!而不是由new operator来分配内存然后调用类型的构造函数!
重载new操作符就是operator new,通过operator new你可以自己决定内存分配方式,是由new来调用的!
还有一个new的用发就是:Class *A = new(nothrow) A(); //这样就能防止返回抛出异常
多谢大牛指点!我在msdn中查到了nothrow这种用法。
程序最后释放掉了pBuffers,但是没有处理pMalloc,指向同一内存释放一个就够了吧?
是不是因为这个原因造成了bounds checker提示memory leak呢?
另外,我使用向导建立了一个Console程序(简单的"hello,world!"程序)然后修改了代码想试一下
但是总提示我:
error C2661: 'new' : no overloaded function takes 2 parameters
是不是需要什么设置?或者我少加了什么头文件?试验程序如下:
#include "stdafx.h"
#include "malloc.h"class Buffers
{
public:
Buffers(int a) { m_a = a; };
~Buffers();
private:
int m_a;
};int main(int argc, char* argv[])
{
void *pMalloc;
Buffers *pBuffer; pMalloc = malloc(16+sizeof(class Buffers));
pBuffer = new (pMalloc) Buffers(1);
printf("pMalloc = %p\n", pMalloc);
printf("pBuffer = %p\n", pBuffer); delete [] pBuffer; return 0;
}
这个不奇怪啊
new() 是对pMalloc对象进行创建
malloc(sizeIn + sizeof(class Buffers))
这个方法是对他分配空间,不过没有具体实现
Buffers()
是Buffers类的构造函数
为指针赋值
但是这种写法很难懂
本人是这样认为的!!!
More Effection C++ 里第8条里有这个的介绍
http://www.csdn.com.cn/program/6728.htm
你提到的防止失败指的是new (nothrow)...这种格式吧?
// C2660 expected
class A {
public:
A(int) { throw "Fail!"; }
};
void F(void)
{
try {
// heap memory pointed to by pa1 will be deallocated
// by calling ::operator delete(void*).
A* pa1 = new A(10);
} catch (...) {
}
try {
// This will call ::operator new(size_t, char*, int).
// When A::A(int) does a throw, we should call
// ::operator delete(void*, char*, int) to deallocate
// the memory pointed to by pa2. Since
// ::operator delete(void*, char*, int) has not been implemented,
// memory will be leaked when the deallocation cannot occur. A* pa2 = new(__FILE__, __LINE__) A(20);
} catch (...) {
}
}