[cpp] view plain copy
- #include <iostream>
- #include <limits>
- using namespace std;
- #define SAFE_DELETE(x) \
- { \
- if (NULL != (x)) \
- { \
- delete (x); \
- (x) = NULL; \
- } \
- }
- #define SAFE_DELETE_ARY(x) \
- { \
- if (NULL != (x)) \
- { \
- delete[] (x); \
- (x) = NULL; \
- } \
- }
- class CA
- {
- public:
- CA()
- {
- setter_m_iTest(-1);
- }
- ~CA() {}
- void setter_m_iTest(int iIn) {m_iTest = iIn;}
- int getter_m_iTest() {return m_iTest;}
- private:
- int m_iTest;
- };
- void fnTestClass();
- void clear_cin();
- int main(int argc, char** argv, char** envp)
- {
- fnTestClass();
- cout << "END, press any key to quit" << endl;
- clear_cin();
- getchar();
- return 0;
- }
- void fnTestClass()
- {
- int i = 0;
- int iTmp = 0;
- const int iCntAry = 4;
- CA* pCaAry = NULL;
- CA* pCa = NULL;
- /** new 单个对象时的内存布局
- + pCa 0x00883e30
- 00883E30 01 00 00 00 .... ///< pCa
- */
- pCa = new CA;
- if (NULL != pCa)
- {
- pCa->setter_m_iTest(1);
- SAFE_DELETE(pCa); ///< delete后, 原来的数据变为 EE FE EE FE
- }
- /** new对象数组时的内存布局
- + pCaAry 0x007d3ddc
- 007D3DD8 04 00 00 00 .... ; ///< 类数组元素个数 = 4
- 007D3DDC 00 00 00 00 .... ; ///< 类数组开始, CA[0]
- 007D3DE0 01 00 00 00 .... ; ///< CA[1]
- 007D3DE4 02 00 00 00 .... ; ///< CA[2]
- 007D3DE8 03 00 00 00 .... ; ///< CA[3]
- */
- pCaAry = new CA[iCntAry];
- if (NULL != pCaAry)
- {
- for (i = 0; i < iCntAry; i++)
- {
- pCaAry[i].setter_m_iTest(i);
- }
- }
- SAFE_DELETE_ARY(pCaAry);
- /** 手工模拟delete删除单个对象
- */
- pCa = new CA;
- if (NULL != pCa)
- {
- pCa->setter_m_iTest(1);
- if (NULL != pCa)
- {
- pCa->~CA();
- free(pCa); ///< ok
- pCa = NULL;
- }
- }
- /** 手工模拟delete删除对象数组
- 会报错, 和实际情况不同
- 以后再研究 :(
- */
- // 会报错, 和实际情况不同
- // pCaAry = new CA[iCntAry];
- // if (NULL != pCaAry)
- // {
- // iTmp = *((int*)pCaAry - 1);
- // for (i = 0; i < iTmp; i++)
- // {
- // pCaAry[i].setter_m_iTest(i);
- // pCaAry[i].~CA();
- // }
- //
- // free(pCaAry); ///< ! crash
- // pCaAry = NULL;
- // }
- // 会报错, 和实际情况不同
- // pCaAry = new CA[iCntAry];
- // if (NULL != pCaAry)
- // {
- // iTmp = *((int*)pCaAry - 1);
- // for (i = 0; i < iTmp; i++)
- // {
- // pCaAry[i].setter_m_iTest(i);
- // pCaAry[i].~CA();
- // free(pCaAry + i); ///< ! crash
- // }
- //
- // pCaAry = NULL;
- // }
- }
- void clear_cin()
- {
- cin.clear();
- cin.sync();
- }
http://blog.csdn.net/lostspeed/article/details/50300867
时间: 2024-11-07 12:43:22