Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Zeblar Nagrim

STD vector question again

This topic is 6297 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!