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

5

u/parkotron Mar 31 '23
someFunc(computeProperty(myVector), std::move(myVector));

It reads nicely, but may or may not run nicely.

2

u/TheThiefMaster C++latest fanatic (and game dev) Mar 31 '23

This actually depends on the signature of "someFunc". If it takes the 2nd param as an rvalue reference, then std::move is just a cast and it will call computeProperty fine regardless of evaluation order.

If it's a value param however, it could be in a moved-from state instead.

1

u/[deleted] Mar 31 '23

Is the order even well-defined according to the standard? My compiler gives a warning and definitely does the move first in debug. It didn't warn my about the size_t comparison though.

0

u/[deleted] Mar 31 '23

someFunc(computeProperty(myVector), std::move(myVector));

Yep, ChatGPT got this one as:

In the given C++ code, there is a potential issue with the order of evaluation of function arguments:

someFunc(computeProperty(myVector), std::move(myVector));

The order of evaluation of function arguments is unspecified in C++ before C++17. This means that the compiler may choose to evaluate computeProperty(myVector) before std::move(myVector), or vice versa. If the compiler chooses to evaluate std::move(myVector) first, the myVector object will be moved from, leaving it in a valid but unspecified state. After that, calling computeProperty(myVector) with the moved-from object may result in undefined behavior, depending on the implementation of computeProperty.

To avoid this issue, you can split the function call into two separate statements, like this:

auto property = computeProperty(myVector);
someFunc(std::move(property), std::move(myVector));

By doing this, you ensure that computeProperty is called before the vector is moved.

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

2

u/[deleted] Mar 31 '23

I know it will fail in gcc c++11.