c++的执行顺序

Execution order of c++

我创建了一个程序来测试 carchive。我想看看保存一百万个数据点需要多快:

#include "stdafx.h"
#include "TestData.h"
#include <iostream>
#include <vector>

using namespace std;

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

int _tmain(int argc, _TCHAR* argv[])
{
    int numOfPoint = 1000000;

    printf("Starting test...\n\n");
    vector<TestData>* dataPoints = new vector<TestData>();

    printf("Creating %i points...\n", numOfPoint);
    for (int i = 0; i < numOfPoint; i++)
    {
        TestData* dataPoint = new TestData();
        dataPoints->push_back(*dataPoint);
    }
    printf("Finished creating points.\n\n");

    printf("Creating archive...\n");
    CFile* pFile = new CFile();
    CFileException e;
    TCHAR* fileName = _T("foo.dat");
    ASSERT(pFile != NULL);
    if (!pFile->Open(fileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive, &e))
    {
        return -1;
    }

    bool bReading = false;
    CArchive* pArchive = NULL;
    try
    {
        pFile->SeekToBegin();
        UINT uMode = (bReading ? CArchive::load : CArchive::store);
        pArchive = new CArchive(pFile, uMode);
        ASSERT(pArchive != NULL);
    }
    catch (CException* pException)
    {
        return -2;
    }
    printf("Finished creating archive.\n\n");

    //SERIALIZING DATA
    printf("Serializing data...\n");
    for (int i = 0; i < dataPoints->size(); i++)
    {
        dataPoints->at(i).serialize(pArchive);
    }
    printf("Finished serializing data.\n\n");

    printf("Cleaning up...\n");
    pArchive->Close();
    delete pArchive;
    pFile->Close();
    delete pFile;
    printf("Finished cleaning up.\n\n");

    printf("Test Complete.\n");

    pause();

    return 0;
}

当我 运行 这段代码时,创建数据点需要一些时间,但随后它 运行 几乎立即完成了其余代码。但是,我必须等待大约 4 分钟才能让应用程序真正完成 运行ning。我假设应用程序会在序列化数据部分等待挂起,就像它在创建数据点期间所做的那样。

所以我的问题是这实际上是如何工作的。 carchive 是否在单独的线程上执行其操作并允许其余代码执行?

如有必要,我可以提供更多信息。

如果你想创建一个包含一百万个默认初始化元素的向量,你只需使用这个版本的构造函数

vector<TestData> dataPoints{numOfPoint};

你应该停止 new 一切,让 RAII 为你处理清理工作。

此外,如果容量不够大,push_back 需要您的向量的 resize,因此如果您从一个空向量开始,并且知道它有多大在最后,你可以提前使用reserve

vector<TestData> dataPoints;
dataPoints.reserve(numOfPoint);
for (int i = 0; i < numOfPoint; i++)
{
    dataPoints->push_back(TestData{});
}