Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ranged for loop const reference doesn't seem to make a difference

Tags:

c++

c++11

If I have a range based for loop in C++11,

for(auto const &ticket : ticketStrip->tickets()) {
  ticket->ClearCalled();
}

Why am I able to call non const methods on the ticket within the loop, such as ClearCalled() when it is not marked as const?

void Ticket::ClearCalled() { ... }

ClearCalled does indeed modify the ticket internals, so it shouldn't be marked as const. I know I should be using

auto &ticket

but I just tried

auto const &ticket

and the compiler accepted it.

The type of ticket is

boost::shared_ptr<AbstractMainStageTicket>

and putting some new code in:

ticket->ClearCalled();
ticket.reset();

makes the compiler flag up the error that reset is not const.

Thanks for your help!

I'm using the GNU 4.6 toolchain for Android.

like image 959
freddy.smith Avatar asked Dec 21 '22 06:12

freddy.smith


1 Answers

From your syntax it seems that ticket is a (smart?) pointer.

ticket->ClearCalled();

Which means that the type of ticket is probably something like

const std::shared_ptr< Ticket >& ticket

What you would need is

const std::shared_ptr< const Ticket >& ticket;
//                     ^^^^^
like image 186
Daniel Frey Avatar answered Dec 24 '22 00:12

Daniel Frey