I've seen a lot of similar questions regarding this topic, but I have seen no explicit answer to this question. Consider the following code:
typedef struct Student
{
int id;
} Student;
vector<Student> students();
for( int i = 0; i < 10; i++ )
{
Student s();
s.id = i
students.push_back( s );
}
How does this vector allocate memory? From my understanding, each Student s
should have it's memory on the stack, and be de-allocated when the loop iterates, so this should produce undefined behaviour if I try and access this data later on. But if I had done the same thing with a vector<int>
it would not produce undefined behaviour.
Is this correct? Either way, my goal is create a vector<Student>
in which the objects are allocated on the heap, without having to use a vector<Student*>
. Is this possible?