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

60 comments sorted by

View all comments

15

u/Stellar_Science Mar 31 '23

Always view subtraction near unsigned types with suspicion. That's why a panel of C++ luminaries unanimously says to avoid unsigned types (at 12:12-13:08, 42:40-45:26, and 1:02:50-1:03:15.)

Their response to the question, "but all ordinals in the standard library, vector size and size_t, they're unsigned", are pretty hilarious:

  • "They're wrong"

  • "We're sorry"

  • "We were young"

4

u/[deleted] Mar 31 '23

You can't really avoid them without constantly doing "narrowing conversions" that the compiler will complain about if you don't write static_cast all over the place.

Implicit conversions with single-parameter constructors combined with templates is the most EVIL thing in c++. The compiler can deduce whatever type fits, and it's often not the one you want. The rules do not seem to make a lot of sense. explicit should be default and conversion constructors should require something extra.

5

u/mark_99 Mar 31 '23

You really can. Here use std::ssize() and ptrdiff_t (or auto). Also no uninitialized vars at the top of functions, it's not C.

Coding guidelines / standards aren't just for fun, they reduce scope for bugs.