技术开发 频道

C++程序开发 让你的代码足够的强大!

  使用数组 delete [ ] 运算符

  如果你分配一个单独的对象,可以直接使用new ,同样你释放单个对象的时候,可以直接使用delete . 然而,申请一个对象数组对象的时候可以使用new,但是释放的时候就不能使用delete ,而必须使用delete[ ]:

// Create an array of objects
CVehicle* paVehicles = new CVehicle[10];
delete [] paVehicles;
// Free pointer to array
paVehicles = NULL; // Set pointer with NULL
or
// Create a buffer of bytes
LPBYTE pBuffer = new BYTE[255];
delete [] pBuffer;
// Free pointer to array
pBuffer = NULL; // Set pointer with NULL

  分配内存

  有时候,程序需要动态分配一段缓冲区,这个缓冲区是在程序运行的时候决定的。例如、你需要读取一个文件的内容,那么你就需要申请该文件大小的缓冲区来保存该文件的内容。在申请这段内存之前,请注意,malloc() or new是不能申请0字节的内存,如不然,将导致malloc() or new函数调用失败。传递错误的参数给malloc() 函数将导致C运行时错误。如下代码展示如何动态申请内存:

// Determine what buffer to allocate.
UINT uBufferSize = GetBufferSize();
LPBYTE
* pBuffer = NULL; // Init pointer to buffer
// Allocate a buffer only if buffer size > 0
if(uBufferSize>0)
pBuffer
= new BYTE[uBufferSize];

  为了进一步了解如何正确的分配内存,你可以读下Secure Coding Best Practices for Memory Allocation in C and C++这篇文章。

  注意使用断言

  Asserts用语调试模式检测先决条件和后置条件。但当我们编译器处于release模式的时候,Asserts在预编阶段被移除。因此,用Asserts是不能够检测我们的程序状态,错误代码如下:

#include <assert.h>
// This function reads a sports car's model from a file
CVehicle* ReadVehicleModelFromFile(LPCTSTR szFileName)
{
CVehicle
* pVehicle = NULL; // Pointer to vehicle object
// Check preconditions
assert(szFileName!=NULL); // This will be removed by preprocessor in Release mode!
assert(_tcslen(szFileName)!=0); // This will be removed in Release mode!
// Open the file
FILE* f = _tfopen(szFileName, _T("rt"));
// Create new CVehicle object
pVehicle = new CVehicle();
// Read vehicle model from file
// Check postcondition
assert(pVehicle->GetWheelCount()==4); // This will be removed in Release mode!
// Return pointer to the vehicle object
return pVehicle;
}

  看看上述的代码,Asserts能够在debug模式下检测我们的程序,在release 模式下却不能。所以我们还是不得不用if()来这步检测操作。正确的代码如下:

CVehicle* ReadVehicleModelFromFile(LPCTSTR szFileName, )
{
CVehicle
* pVehicle = NULL; // Pointer to vehicle object
// Check preconditions
assert(szFileName!=NULL); // This will be removed by preprocessor in Release mode!
assert(_tcslen(szFileName)!=0); // This will be removed in Release mode!
if(szFileName==NULL || _tcslen(szFileName)==0)
return NULL; // Invalid input parameter
// Open the file
FILE* f = _tfopen(szFileName, _T("rt"));
// Create new CVehicle object
pVehicle = new CVehicle();
// Read vehicle model from file
// Check postcondition
assert(pVehicle->GetWheelCount()==4); // This will be removed in Release mode!
if(pVehicle->GetWheelCount()!=4)
{
// Oops... an invalid wheel count was encountered!
delete pVehicle;
pVehicle
= NULL;
}
// Return pointer to the vehicle object
return pVehicle;
}
0
相关文章