简体   繁体   中英

the pointer to a reference in c++

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?

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_p and the vector myspa and no mysterious third "thing". Instead, think of the reference as a way to grant access to an object (here myspa 's first element) in situ, without copying it anywhere.

So, myspa.at(0) grants direct access to the initial Myspa object inside the myspa vector. 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 pointer myspa_p .

This code compile.. Variable myspa_p point to the first element of the vector myspa.

myspa_p contains left-value of first element of the vector!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM