+ 3

How does vector::data actually work?

Why Hello is printed twice? https://code.sololearn.com/c8ykzB4xK22r/?ref=app

7th Dec 2017, 7:24 PM
wave rider
wave rider - avatar
3 Answers
+ 2
vector::data returns a pointer to the beginning of the array used in the vector. Are you confused that b still prints hello even after you clear? That's because clear isn't guarenteed to free the memory, the memory is still owned by the vector. Then when you ask for the pointer to the beginning of the array again hello is still in it and so you print it again.
7th Dec 2017, 8:02 PM
Dennis
Dennis - avatar
+ 2
Thanks, @Dennis it makes more sense now. So who is responsible for clearing the memory? Imagine my vector was containing some sensitive data? I want clear actually clear the memory used by the vector
7th Dec 2017, 9:25 PM
wave rider
wave rider - avatar
+ 2
I think actually freeing memory the normal way is only done in destruction, but I'm not too sure there. Something I usually do is swapping the vector with a temporary vector, since the temporary vector is still completely empty the other vector will become empty. You can do a 1 liner like this: std::vector<int> v{ 1,2,3,4 }; // The vector we want to clear std::vector<int>().swap( v ); // and it's gone :) Now when you print the address of v's data std::cout << v.data(); // This should print 0, meaning it's pointing at nothing.
7th Dec 2017, 9:47 PM
Dennis
Dennis - avatar