jeudi 23 juillet 2015

C++ memory preallocation for vector via constructor fails

I use VS2013. I discovered some strange behavior. When I reserve memory using the reserve method, the code works, but when I reserve via constructor, it throws bad_alloc

const int elemNumber = 100000000;
try
{
    //std::vector<int>* intVector = new std::vector<int>(elemNumber); // throws bad_alloc
    std::vector<int>* intVector = new std::vector<int>();
    intVector->reserve(elemNumber); //OK

    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();

    for (int i = 0; i < elemNumber; ++i)
    {
        intVector->push_back(i);
    }

    end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::cout << "Time interval: " << elapsed_seconds.count() << endl;
    delete intVector;
    cout << "Done" << endl;
}
catch (bad_alloc exc)
{
    cout << exc.what() << endl;
}

What could be the reason?

Aucun commentaire:

Enregistrer un commentaire