vector question

Started by
2 comments, last by Nazrix 17 years ago
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
Advertisement
Yes it would.

You are storing the object by value into the vector.
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 only, and not for things themselves." - John Locke
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

This topic is closed to new replies.

Advertisement