When looking over the member functions of the STL containers, an odd thought occurred to me. Why don't functions like std::vector<T>::push_back(T)
not have an (optional) return value (iterator or even a reference to the appended object)? I know std::string
functions like insert
and erase
return iterators, but that's for obvious reasons. I'd think it'd often save a second line of code that often follows these function calls.
I'm sure the designers of C++ have a very good reason, please enlighten me :)
UPDATE: I'm including a real-world code example here where it could reduce code length:
if( m_token != "{" )
{
m_targets.push_back( unique_ptr<Target>(new Dough(m_token)) );
return new InnerState( *(m_targets.back()), this );
}
could be reduced to
if( m_token != "{" )
return new InnerState( *(m_targets.push_back( unique_ptr<Target>(new Dough(m_token)) )), this );
If I assume std::list::push_back
returns a reference to the added element. The code is a bit heavy, but that's mostly (two sets of parentheses) due to unique_ptr
's constructor and dereferencing it. Perhaps for clarity a version without any pointers:
if( m_token != "{" )
{
m_targets.push_back( Dough(m_token) );
return new InnerState( m_targets.back(), this );
}
vs.
if( m_token != "{" )
return new InnerState( m_targets.push_back( Dough(m_token) ), this );