Chinaunix

标题: 模板出现的问题,高手请进帮忙分析一下。 [打印本页]

作者: chenlihuiabc    时间: 2007-11-05 13:28
标题: 模板出现的问题,高手请进帮忙分析一下。
test.h

#include "stdio.h"
#include "stdlib.h"
#inlcude <string>

using namespace std;

template <class T>
class TObjNew {
   T* _t;
public:
   TObjNew(void* _p, const int nCount) {
          _t = (T*)_p;
         _t = new(_t) T[nCount];
   }
   ~TObjNew() {
    delete [] _t;
  }
};

test.cpp

#include "test.h"
struct STest {
     string m_strTmp;
     int m_nTmp;
};

char* pTmp = new char[1024];

int main(int argc, char** argv) {
    TObjNew<STest> obj(pTmp,  4);
    return 0;
}

为什么在析构的时候,会报内存错误而崩掉。
经调试,发现在在调用析构的时候又调用了构造函数,请高手分析以上程序的错误之处。感谢。

[ 本帖最后由 chenlihuiabc 于 2007-11-5 13:30 编辑 ]
作者: yecheng_110    时间: 2007-11-05 13:48
_t = new(_t) T[nCount];
这是什么?
作者: chenlihuiabc    时间: 2007-11-05 13:56
这是在已有的内存上构造对象。
作者: 飞灰橙    时间: 2007-11-05 14:03
兩個問題:
1. _t = new(_t) T[nCount];
    和delete [] _t; 不匹配
    對同一個堆放,你不能用自己決定分配空間的new,又用系統自動釋放空間的delete

2. new(_t) T[nCount], 需要的空間大小不一定是 sizeof(T) * nCount,
    也不一定是 sizeof( T[nCount] ), 這也是vs2005曾經讓我無比不爽的地方
作者: wb2007    时间: 2007-11-05 15:39
TObjNew(void* _p, const int nCount) {
          _t = (T*)_p;
         _t = new(_t) T[nCount];
   }


内存泄漏了。
作者: abomber    时间: 2007-11-05 16:20
placement new的 内存 要小心

不能用delete释放 否则可能释放2次
作者: abomber    时间: 2007-11-05 16:22
直接用

for(int i = 0; i < nCount;++i)
{
       _t.~T();
      ++_t;
}
作者: chenlihuiabc    时间: 2007-11-05 17:02
我参看stl中的写法,和楼上说的一致,
调用delete会把原先的内存释放给操作系统,所以必须显示调用析构函数。这样才能达到内存公用的目的。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2