Fixed bug identified in #3589 for the v4.0 branch

This fix is the same fix done in #3596 for the master branch.