I saw some code in c++, which is a little bit confusing for me:
class Myspa {};
vector<Myspa> myspa;
Myspa * myspa_p;
myspa_p = &myspa.at(0);
vector.at() function will return a reference of the element, myspa_p is a pointer, so what does the myspa_p = &myspa.at(0) mean?
When you return a reference, don’t think of a reference as being a distinct type/object of data to which a pointer can point – there’s just the pointer
myspa_pand the vectormyspaand no mysterious third “thing”. Instead, think of the reference as a way to grant access to an object (heremyspa‘s first element) in situ, without copying it anywhere.So,
myspa.at(0)grants direct access to the initial Myspa object inside themyspavector. Then, the addition of a leading&– forming&myspa.at(0)– simply asks for the address of that initial object – hence the address can be stored in the pointermyspa_p.