Home > Software design >  Visual Studio no displays the correct length of std::vector
Visual Studio no displays the correct length of std::vector

Time:12-10

I have this piece of code when I try to debug it to see how many elements there are in std::vector then Visual Studio writes that the length of the vector is zero and I do not know how to fix it (I build in DEBUG mode)

auto foo()
{
    std::vector<int> bar = { 1, 2, 3, 4, 5 };
    return bar;
}
int main()
{
    foo();

}

screenshot

At first, I thought it was in the IDE, I tried to use Clean, but the result did not change, I decided to reinstall MSVC because I thought it was in it and I didn't come to anything either.

CodePudding user response:

This is a known bug in MSVC.

NRVO bug in MSVC

Solution is to add /Zc:nrvo- to the c compiler's additional options at Properties->Debug->C/C ->CommandLine

// recent versions of MSVC2022
#include <vector>
using std::vector;
auto foo()
{
    std::vector<int> bar = { 1, 2, 3, 4, 5 };
    return bar;     // in debug mode, bar has size 0 unless /Fc:nrvo- flag is added
}
int main()
{
    auto x = foo(); // x is shown properly
}
  • Related