is it nessisary to dynamicly creat inside vectors?

Started by
7 comments, last by graveyard filla 19 years, 6 months ago
TOPIC^ should i do something like this block i; Worm_Blocks.push_back(i); or do this block i = new block; Worm_Blocks.push_back(i); dose it matter?
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Advertisement
It depends if your vector is a vector of objects or object pointers. Usually you can just specify objects, but be careful for non-POD types, since you need the copy constructor and assignment operator working properly. I tend to use a vector of object pointers for complex types.
Stick with the first one :) why use the second one? 1) It more complex 2) You will have to remember to delete it to free memory 3) acessing it will be slower
4)the other way gives me errors any way
thanks for the help both of you
[smile]
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Quote:Original post by raptorstrike
4)the other way gives me errors any way

"The other way" is correct if you have a vector<block*> rather than a vector<block>, which you can perfectly well do. In most cases, however, you don't want to.
Unless you're using derived classes and storing the base-class pointer in the vector - for example, a master entity list.
Ooops - should have added - if you are storing dynamic objects, instead of having to think of a new unique name for each you can just use:

worm_blocks.push_back(new block());
yeah but i have to refrence to it latter in the function and still maintain the previous .back for comparison perposes (so i cant just do .back)
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
huh ?? you should be able to do exactly the same things with dynamically allocated objects as you can with static objects. well, i guess technically they aren't static, since the vector is doing the allocating for you...

the point is though, you can do the same stuff. in some situations, using pointers is required... for example, if you want to take advantage of polymorphism (you will one day). for polymorphism to work, dynamic memory is a must.

FTA, my 2D futuristic action MMORPG

This topic is closed to new replies.

Advertisement