freddy.smith
freddy.smith

Reputation: 461

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

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.

Upvotes: 4

Views: 229

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56863

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;
//                     ^^^^^

Upvotes: 11

Related Questions