The explanation of what you're seeing is that std::vector
doesn't follow the same rules of array decaying like a raw c-style array does:
#include <iostream>
using std::cout;
using std::endl;
int main() {
int a[] ={3,5,8};
cout<<"raw array object address: "<<&a<<endl;
cout<<"raw array object address +1: "<<&a+1<<endl; // adds sizeof(a)
cout<<"raw array data[0] address: "<<&a[0]<<endl; // same as a + 0
cout<<"raw array data[1] address: "<<&a[1]<<endl; // same as a + sizeof(int)
}
Outputs:
raw array object address: 0x7ffd02ca2eb4
raw array object address +1: 0x7ffd02ca2ec0
raw array data[0] address: 0x7ffd02ca2eb4
raw array data[1] address: 0x7ffd02ca2eb8
See live demo
Can anyone explain to me how vector object works?
A std::vector
instance is a non POD variable, and will have it's own address at the local storage. It merely wraps the underlying memory address that is actually used to store the data. How exactly is implementation defined, but you can consider that there's at least an interned pointer, and an allocator concept is used to obtain the memory.
Keeping track of the current size, and copying to reallocated memory is managed as well.
The std::vector::data()
functions are dedicated to access that guaranteed contiguous chunk of memory.
You should notice that the pointers you obtain through the mentioned data()
functions aren't stable, and may get invalidated as soon the std::vector
is manipulated in a way.
Also worth mentioning that std::array
makes an exception here from the other standard containers:
#include <iostream>
#include <array>
using std::array;
using std::cout;
using std::endl;
int main() {
array<int,3> a ={3,5,8};
cout<<"std::array object address: "<<&a<<endl; // Note these addresses ...
cout<<"std::array object address +1: "<<&a+1<<endl;
cout<<"std::array data[0] address: "<<&a[0]<<endl; // are the same
cout<<"std::array data[1] address: "<<&a[1]<<endl;
}
Outputs:
std::array object address: 0x7ffe72f1cf24
std::array object address +1: 0x7ffe72f1cf30
std::array data[0] address: 0x7ffe72f1cf24
std::array data[1] address: 0x7ffe72f1cf28
Live demo