简体   繁体   中英

Return array of pointers by reference

Inside one of my classes i've got a

Reservation * availability[30] = {nullptr};

(which I of course initialize later with some values).

Nevertheless, I've got a getReservations() function which is supposed to return a reference to that array of 30 elements, so that it can be used like:

getReservations()[i] ...

How should I declare that function?

The syntax for declaring a function that returns the array by reference is this:

Reservation * (& getReservations())[30];

Of course, as you can see, you shouldn't use this in real life. Instead do it with a type alias:

using Reservations = Reservation * [30];

Reservations & getReservations();

Or, because arrays aren't bounds-checked anyway, just return a pointer which you can then index like an array:

Reservation * getReservations();
Reservation *(&getReservations())[30];

should do it for you.

Please remember of dangling references and pointer management.

I would recommend you to use modern C++:

using ReservationArray = std::array<Reservation*, 30>;

ReservationArray _availability;

and to return that as:

ReservationArray& getReservations()

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