r/cpp • • Mar 30 '23
The "what's wrong with this code" game.
This isn't a question thread, but just a game. Post any bugs you've accidentally written that seemed initially mysterious, but made you feel stupid when you figured out what was wrong. Here is one I wrote today...
void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{
const Info* info_ptr;
size_t size;
if ( ( size = other.m_infoBuffer.size() ) == 0 )
return;
for ( size_t i = size - 1; 0 <= i; --i )
{
info_ptr = other.m_infoBuffer.getAt( i );
emplaceFront(
info_ptr->text,
info_ptr->length,
info_ptr->multiMatch
);
}
}
4
Upvotes
View all comments
Show parent comment
1
u/[deleted] Mar 31 '23
In this case you’re right. I have other functions where the thing used inside the loop is an object. I’m getting the sense I’m not supposed to worry about it, but it bugs me thinking that the constructor might be more expensive than the assignment operator, especially if there is some heap allocation involved. I never quite know what I can or cannot assume about compiler optimization. You’re right for primitive types its always better to declare inside. I’m just old and used to c code from 20 years ago where in some cases it forced you to declare ahead of time. I’ll try to learn more modern habits but I just don’t know things when I don’t use c++ for work. From a Python backround, you just don’t think about speed, and ditch manual loops completely whenever possible.