For loop causing weird behavior

This code works and draws the camera image:

//ofApp.h
class CameraPlayer
{
public:
	ofPixels pix;
	void update(ofVideoGrabber& cam)
	{
		if (cam.isFrameNew())
		{
			pix = cam.getPixels();
		}
	}
	void draw()
	{
		ofTexture tex;
		tex.loadData(pix);
		tex.draw(0, 0, ofGetWidth(), ofGetHeight());
	}
};

class ofApp : public ofBaseApp{

	public:
		void setup();
		void update();
		void draw();

		ofVideoGrabber cam;
		CameraPlayer cp;
		std::vector<CameraPlayer> cps;
};
//ofApp.cpp
void ofApp::setup(){
	cam.setDeviceID(1);
	cam.initGrabber(800, 450); //Not my main question, but what's the diff. between this & cam.setup(800,450) ?
	cam.setDesiredFrameRate(30);

	CameraPlayer c;
	cps.push_back(c);
}

void ofApp::update(){
	cam.update();
	if(cam.isFrameNew())
	{		
		cps[0].update(cam);
	}
}

//--------------------------------------------------------------
void ofApp::draw(){	
	cps[0].draw();
}

However, if I replace
cps[0].update(cam);
with

for (CameraPlayer cp : cps)
		{
			cp.update(cam);
		}

it does NOT draw the image. Why?

In the case of the former, I get the errors

[ error ] ofTexture: allocate(): ofTextureData has 0 width and/or height: 0x0
[warning] ofGLRenderer: draw(): texture is not allocated
[ error ] ofGLUtils: ofGetGLFormatFromPixelFormat(): unknown OF pixel format OF_PIXELS_UNKNOWN, returning GL_LUMINANCE
[ error ] ofGLUtils: ofGetGLInternalFormatFromPixelFormat(): unknown OF pixel format OF_PIXELS_UNKNOWN, returning GL_RGBA

but they stop. soon after starting the program. In the latter case, they continue forever.

Using an int-based for-loop instead works though.

		for (int i = 0; i < cps.size(); ++i)
		{
			cps[i].update(cam);
		}

Is there something about the for (Type X: x) style of loop that I don’t know? Never had a problem with them before, though I guess I don’t use them that often.

Try this instead

for (CameraPlayer & cp : cps)

this actually copy your cp object and destroy after code block {}. no data is altered in cps vector.

for (CameraPlayer cp : cps)

Ahhh, I should’ve known c++ would pull something like this. Thank you!