Jump to content
  • Advertisement
Sign in to follow this  

STL vector coding practice

This topic is 5472 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 I have a class with constuctor and destructor. I want to construct object of this class and add it to the end o the std::vector, so I do the following:
std::vector<MyClass> v;
 MyClass obj; //MyClass' constructor is invoked (for obj)
   ...do something with obj...
 v.push_back(obj); //MyClass' constructor is invoked (for v[.])
 //MyClass' destructor is invoked (for obj)

So how should I write this code to avoid the unnecessary constructor and destructor calls?

Share this post

Link to post
Share on other sites
first of all, why do you want to avoid calling the contructor / destructor?

secondly, calling v.push_back() will NOT call the constructor for the object, rather, the copy constructor. you gotta be carefull with this, especially if dynamic memory is involved with the class.

last, you can avoid using the contructor i guess by just putting the object directly into the vector upon creation.


you can then acess that object via v.back().

Share this post

Link to post
Share on other sites
Use dynamic memory and store pointers instead of objects.

std::vector<Object*> list; // list of pointers

list.push_back( new Object(parameters) ); // add a new pointer to the list

list.back()->SomeFunction(); // do things with new Object;

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!