Skip to main content
GameDev.net gamedev.net
🔒 Locked

vector question

Started by Nazrix Mar 30, 2007 at 11:35 PM 2 replies 1.6k views
Original Post
Nazrix
Nazrix
Let's say I have a class called AClass, a STL vector called listOfSomeClass that's a list of variables of type someClass.


class AClass
{
	vector <someClass> listOfSomeClass;

	void someFunction()
	{
		SomeClass foo;
		listofSomeClass.push_back(foo);
	}

};


My question is if I call the function, AClass.someFucntion() and it pushes a SomeClass into the vector list does the object foo get lost after someFunction done executing? In other words if I were to access it using SomeClass.listOfSomeClass[0] would it be a valid object?
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
dave
dave
Yes it would.

You are storing the object by value into the vector.
Agony
Agony
push_back() creates a copy of its parameter. The copy remains valid, but the original goes out of scope and is no longer valid. As long as SomeClass is simple and can use the default copy constructor, or you have properly written your own copy constructor and assignment operator, then everything will be fine. But you can't refer to a reference or pointer to the local object that was pushed back outside of the function. Any pointer or reference to that object becomes invalid outside of the function, and the copy inside the vector has a different pointer/reference, since they are different instances (although identical in terms of content).
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
Nazrix
Nazrix
Thanks for the help. I realize I do need a copy constructor since I have pointers involved.
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.