C++ Containers of pointers -


i have been pondering issue today , it's difficult find answer on google.

i'm trying understand stl container behaviour when dealing pointers both objects allocated on heap, , on stack.

so, start objects, no pointers ... imagine have ...

std::vector<int> myvec; while(true) {     int myint = 5;     myvec.push_back(myint);     myvec.pop_back(); } 

my understanding pop_back() method ensure integers contained in vector deleted, not removed container. if ran , did billion iterations, should not expect leak memory. insert, deleted. memory check shows behaviour.

now consider use vector of pointers (to objects on heap) ...

std::vector<int*> myvec; while(true) {     int * myintp = new int(5);     myvec.push_back(myintp);     myvec.pop_back(); } 

in case, pointer ought removed each time pop_back() called, , underlying object remains un-deleted, causing memory leak. after billion iterations have quite significant memory being used, though have no entries in vector.

now if have vector of pointers (to objects on stack) ...

std::vector<int*> myvec; while(true) {     int myint = 5;     int * myintp = &myint;     myvec.push_back(myintp);     myvec.pop_back(); } 

here pointers point stack objects. memory freed in call pop_back(), or not? memory check showed me behaviour no memory leaked. small amount of memory used, indicated behaved objects on stack. not expected me, because if pointer had been passed me function, stack variable i.e.

void myfunc(int * myintp) {     std::vector<int*> myvec;     myvec.push_back(myintp);     myvec.pop_back(); } int main() {     int myint = 5;                                                                                                                           int * myintp = &myint;     myfunc(myintp);     std::cout << (*myintp) << std::endl;     return 0; } 

then allowing vector free memory, render myintp pointing removed data. surely can't correct?

could explain?

also there name "a pointer pointing variable on stack" i.e. not initialised "new"?

thanks

joey

while(true) {     int myint = 5;     int * myintp = &myint;     myvec.push_back(myintp);     myvec.pop_back(); } 

you have 1 int here, myint value of 5. loop re-use same one. push pointer 1 int vector , remove it. nothing else happening. there isn't memory leak because not allocating new ints.

std containers nothing different pointers 32/64 bit interger. far care, pointer number. so, if insert pointer container, your responsibility delete it.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -