Vector of Structures - Memory

Hi all,

I would like to know what would happen in the following scenario

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct my_struct{
    int a;
    int b[4];
};

class A{


void foo(){
    my_struct a;
    vecs.push_back(a);
}

private:
    std::vector<my_struct> vecs;
};


I have following questions:
1. Based on my understanding "a" in line 10 is in stack. Is it?
2. What happens to vecs element once we come out of the function "foo"?
3. What is correct way to vector of structures? How to make sure no memory leak?

Thanks.
Method push_back creates a new object in the vector and copies to it the argument you specified. So there is no problem that object 'a' is created in the stack.
And How do I handle freeing up memory for this vector?
You can use the following member functions

void resize(size_type sz, bool c = false);
size_type capacity() const noexcept;
void reserve(size_type n);
void shrink_to_fit();
iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);
closed account (zb0S216C)
rachitagrawal wrote:
"And How do I handle freeing up memory for this vector?"

There's nothing to clear up since it's the std::vector's job - it allocated the memory, it should free it.

Wazzak
Thanks Wazzak and Vlad...

Another quick questions

 
std::vector<my_struct> a(10, my_struct());


Is the above same statement same as assigning memory with "new" operator? What I want to ask is, do I have to free up the memory manually or compiler will take care of it automatically?

Thanks.
The vector will take care of it automatically. Its destructor deletes all memory that it allocates, so as soon as the vector goes out of scope, any memory associated with it gets deleted.

The constructor you give forces the vector to allocate enough memory for 10 instances of my_struct, and then fills that memory with the second argument, or a default constructed my_struct.
Topic archived. No new replies allowed.