class AClass
{
vector <someClass> listOfSomeClass;
void someFunction()
{
SomeClass foo;
listofSomeClass.push_back(foo);
}
};
vector question
Let's say I have a class called AClass, a STL vector called listOfSomeClass that's a list of variables of type someClass.
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?
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).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement