Chưa phân loại

C++ Tutorial – Safe deleting a vector

Hi everyone, I’ll give you a code snippet for safe-deleting a vector (or any STL container) in C++.

Case 1, If your vector that are holding pointer elements. You should do exactly this code for safe reason

if(this->myVector!= NULL)
	{
		for (unsigned int index = 0; index < this->myVector->size(); index++)
		{
			delete (this->myVector->at(index));
		}
		delete this->myVector;
		this->myVector= NULL;
	}

If your vector is simply hold value, you’ll have a simple code as:

if(this->myVector!= NULL)
	{
		delete this->myVector;
		this->myVector= NULL;
	}

Happy coding!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s