std::list question

Started by
12 comments, last by Neen10do 21 years, 2 months ago
up

i code therefore i am.
----------------------i code therefore i am.Aero DX - Coming to a bored Monitor near you!
Advertisement
If you are going to use newSprite beyond
the scope of the function you are in , you
need to allocate heap space.

//example
cSprite newSprite = new cSprite;
if(NULL == newSprite);...//Handle error here
newSprite->Define(<snip>;
newSprite->SetBitmap(<snip>;
...
ShipBullets.AddNode(newSprite);
//end example

Another tip is to check the return value of all
of your functions. Certainly all memory
allocates need to be checked.

Finally, make sure all of your variables are initialized
properly in the cSpriteList constructor.

BTW: Why did you change void cSpriteList::AddNode(cSprite* Sprite) to void cSpriteList::AddNode(cSprite Sprite)? The new
routine will have Head pointing to garbage as soon the function
returns since cSprite Sprite is created in local stack space.
i would not need to allocate memory for the sprite because i allocate memory for the node in AddNode() (and the sprite is within the node). i modified the class to work with integers, and it works fine, but for some reason it doesn''t work with my csprite class, any suggestions?
----------------------i code therefore i am.Aero DX - Coming to a bored Monitor near you!
When you call AddNode(cSprite Sprite), the Sprite is copy constructed upon entering the function and assignment copied when assigning to newNode->mySprite. You DID define both the copy constructor and assignment operator for class cSprite right? If you do so, your program shouldn''t crash anymore.

Regardless though, passing the cSprite in by value is a bad idea. The time it takes for the copy construction and assigment copy is unnecessary and its just bad form for the list to have its own, personal copy of the sprite. What will you do when you want to get it out of the list? Copy it again? Have the nodes store pointers to the cSprite like you originally did. Then the copy and assignment operators will never be called and you will have only 1 instance of the sprite loaded in memory, like you should.

Storing an integer in node is "basically equivalent" to storing a pointer to the cSprite.

This topic is closed to new replies.

Advertisement