user823738
user823738

Reputation: 17521

Is const_cast(iterator->second) safe?

I want to know if this code is safe and doesnt have any undefined behavior.

 QueueMap::const_iterator it = m_3playersQueue.find(s->m_GameCode);
 if(it == m_3playersQueue.end())
 {
     std::deque<Session*> stack;
     stack.push_back(s);

     m_3playersQueue[s->m_GameCode] = stack;
     return;
 }

 const_cast<std::deque<Session*>&>(it->second).push_back(s);

 QueueMap is of type std::tr1::unordered_map< uint32, std::deque<Session*> >

Upvotes: 0

Views: 659

Answers (3)

xan
xan

Reputation: 7731

Yes, it is safe. Even if a const_iterator is different from an iterator, the objects in the map are the same. As long as all the map contents were created as mutable std::deque<Session*> objects, it's OK to cast the constness away.

Of course, it's possible you're violating some invariant the constness was meant to convey, but that's possible with any const_cast taken in isolation.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476990

The code might be a bit simpler to understand in the following form: Always insert and update:

std::pair<QueueMap::iterator, bool> p =
  m_3playersQueue.insert(std::make_pair(s->m_GameCode, std::deque<Session*>()));

p.first->second.push_back(s);

The only inefficiency is when the element already exists, in which case you have to throw away an empty deque. But small, short-lived heap allocations aren't usually expensive, so you should profile carefully to justify more complicated code. Think about how long it would take your successor to work through and debug your code!

Upvotes: 1

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29529

Your code contradicts itself. Just use QueueMap::iterator instead of QueueMap::const_iterator.

What you're doing is explicitly making it const, then const_casting away the constness. Why bother?

Upvotes: 4

Related Questions