Advertisement

STD vector question again

Started by June 24, 2001 03:31 PM
1 comment, last by Zeblar Nagrim 23 years, 7 months ago
Hi! Is this a proper use of a strings vector?
  

#define SAFE_DELETE_FIELD(ob) if(ob) {delete[] ob; ob = NULL;} 

// In a class I have this STL vector with char pointers

std::vector <char*> m_vObjectNames;

// Somewhere in a func in the code I do this:

char *Name;
				
Name = new char[ 1 + (mChunk->mBytes)];
strcpy(Name, (char *)mBuffer);
m_vObjectNames.push_back(Name);				

// I can´t remove Name now

// becuase m_vObjectNames[curr_element] 

// use this memory


// In the destructor I remove the memory

int NumberOfString = m_vObjectNames.size();

for(int i=0; i<NumberOfString; i++)
	SAFE_DELETE_FIELD(m_vObjectNames[i]);

m_vObjectNames.clear();

  
Thanks, Zeblar Nagrim, Lord of Chaos
It looks ok.
Just a small tip: You don''t have to call vector::clear() since the vector will clear itself upon destruction.

Snale
+--My humble and superior homepage
Advertisement
the code is ok, but

You should actually be using std::string. that way you don`t need to worry about memory allocation and deallocation.



    #include <strings>#include <vector>//later in the code ....std::vector<std::string> myStrVector;std::string myFirstString = "hello";myStrVector.push_back( myFirstString );//later for destruction...//nothing to do!!!!!!! string destructor will free the memory of the strings and vector will clean up itself.    


This is actually very efficient, because most implementation of the stl string uses reference counted pointers, so when you push_back the string, the only thing that is copied is actually an internal pointer.

Edited by - Gorg on June 24, 2001 8:22:44 PM

This topic is closed to new replies.

Advertisement