c++ - Different addresses while filling a std::vector -


wouldn't expect addresses printed 2 loops same? was, , cannot understand why (sometimes) different.

#include <iostream> #include <vector> using namespace std;  struct s {   void print_address() {     cout << << endl;   } };  int main(int argc,char *argv[]) {   vector<s> v;   (size_t = 0; < 10; i++) {     v.push_back( s() );     v.back().print_address();   }   cout << endl;   (size_t = 0; < v.size(); i++) {     v[i].print_address();   }    return 0; } 

i tested code many local , on-line compilers , output looks (the last 3 figures same):

0xaec010 0xaec031 0xaec012 0xaec013 0xaec034 0xaec035 0xaec036 0xaec037 0xaec018 0xaec019  0xaec010 0xaec011 0xaec012 0xaec013 0xaec014 0xaec015 0xaec016 0xaec017 0xaec018 0xaec019 

i spotted because making initialization in first loop obtained uninitialized object in subsequent part of program. missing something?

the vector performing re-allocations in order grow needed. each time this, allocates larger buffer data , copies elements across. can see in first loop, each address jump followed larger sequence of consecutive addresses. in second loop, @ addresses after final reallocation.

0xaec010 0xaec031  <-- 0xaec012  <-- 0xaec013 0xaec034  <-- 0xaec035 0xaec036 0xaec037 0xaec018  <-- 0xaec019 

the simplest way instantiate vector 10 s objects be

std::vector<s> v(10); 

this involve no re-allocations. see std::vector::reserve.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -