我使用VS2013 (Win7 64)。我发现了一些奇怪的行为。当我使用备用方法预留内存时,代码可以工作,但是当我通过构造函数保留内存时,它会抛出bad_alloc。
const int elemNumber = 100000000; //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; }
可能是什么原因?
发布于 2015-07-23 11:52:38
请看下面的示例:
#include <iostream> #include <chrono> #include <vector> int main() const int elemNumber = 5; std::vector<int> intVector(elemNumber); // throws bad_alloc std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); for (int i = 0; i < elemNumber; ++i) //intVector[i] = i; intVector.push_back(i); //prints the vector for (auto& i : intVector) std::cout << i << std::endl; end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Time interval: " << elapsed_seconds.count() << std::endl; std::cout << "Done" << std::endl; catch (std::bad_alloc exc) std::cout << exc.what() << std::endl; std::cin.get();