Advertisement Jump to content
Sign in to follow this  

returning a reference to stl list

This topic is 4916 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

I get null values when I try to get the position of something from my list so my first thought was maybe I wasn't returning a reference to my list correctly here is its implementation: C++
 list<Bullet*>& Character::getBullets()
	return bullets;

Here is some other information that might show a problem if that is the correct way to return a reference to the list I store bulllets that I shoot in a list. Here is my shoot function where I add a bullet to the list: C++
void Character::shoot()
	bullets.push_back(new Bullet(bulletID, curWep.getDmg(), curWep.getRange(), direction, 
					  x, y)); 

I then have a display class that updates the screen in their I have this: psuedo code: if player presses space shoot. I have check this it does do the shoot function when I press space bar C++
list<Bullet*>::iterator bulletsIter;
for (bulletsIter = player.getBullets().begin(); bulletsIter != player.getBullets().end(); bulletsIter++)
					//if ((*bulletsIter)->getMonID() == (*mon).getMonID())
						//return *(*monstersIterator);
						bX = (*bulletsIter)->getPosX();
						bY = (*bulletsIter)->getPosY();

note: player inherits getBullets from character.

Share this post

Link to post
Share on other sites
There's nothing wrong with your syntax. Consider this simplified version of what you've described:

#include "stdafx.h"
#include <iostream>
#include <list>

struct Bullet {
static int s_nextID;
int ID;
Bullet():ID(s_nextID++) {}
int Bullet::s_nextID = 0;

class Projectiles {
std::list<Bullet*> bullets;
std::list<Bullet*>& GetBullets() { return bullets; }
void Shoot() {
bullets.push_back(new Bullet());

int _tmain(int argc, _TCHAR* argv[])
Projectiles proj;

for (std::list<Bullet*>::iterator bullet = proj.GetBullets().begin();
bullet != proj.GetBullets().end();
std::cout << "Bullet in the air:" << (*bullet)->ID << '\n';
char c;
std::cin >> c;

return 0;


Bullet in the air:0
Bullet in the air:1
Bullet in the air:2

You'll need to find the problem in an unexpected area of your code. Trace your bullet pointers and see where they are allocated and deallocated.

Share this post

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

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. 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!