删除时C ++ unique_ptr问题

时间:2016-02-22 20:38:57

标签: c++ dictionary unique-ptr

尝试工作并理解c ++ unique_ptr ...我创建了一些用于管理资源的类并使用unique_ptr ....所有工作都很好但是退出程序Visual Studio崩溃时出现断言错误(is_block_type_valid(header-> _block_use)我不明白为什么......有人可以帮助我吗?

#pragma once

#include <memory>
#include <string>
#include <map>

// Include DevIL library to load image files.
//
#include "..\..\Libraries\DevIL\include\IL\il.h"

typedef unsigned char uchar;


class Resource
{
public:
    std::string mFileName;
    std::unique_ptr<uchar[]> mRawData;

    Resource(std::string fileName) : mFileName(fileName) {}

    virtual void Load() = 0;
};

class ResourceBitmap : public Resource
{
private:
    int mSizeX, mSizeY, mBpp;

public:
    ResourceBitmap(std::string fileName) : Resource(fileName) {}

    void Load() override
    {
        ilInit();
        ILubyte imageId = ilGenImage();
        ilBindImage(imageId);

        if (!ilLoadImage(mFileName.c_str()))
        {
            // Error loading image
        }

        mSizeX  = ilGetInteger(IL_IMAGE_WIDTH);
        mSizeY  = ilGetInteger(IL_IMAGE_HEIGHT);
        mBpp    = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

        mRawData = std::move(std::unique_ptr<uchar[]>(ilGetData()));    // unique_ptr constructor with the raw pointer returned by DevIL
    }
};

class ResourceSound : public Resource
{
public:
    void Load() override
    {

    }
};

class ResourceManager
{
public:
    std::map<std::string, std::unique_ptr<Resource>> mResources;

    void AddResource(std::unique_ptr<Resource> resource)
    {
        auto it = mResources.find(resource->mFileName);
        if (it == mResources.end())
        {
            resource->Load();
            mResources[resource->mFileName] = std::move(resource);
        }
    }
};



#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

#include <Windows.h>

#include "Resource.h"

#pragma comment(lib, "DevIL.lib")

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    {
        std::unique_ptr<ResourceManager> resourceManager = std::make_unique<ResourceManager>();

        resourceManager->AddResource(std::move(std::make_unique<ResourceBitmap>("d:\\mojito.jpg")));
        //resourceManager->AddResource(std::move(std::make_unique<ResourceBitmap>("d:\\petalo.jpg")));
        //resourceManager->AddResource(std::move(std::make_unique<ResourceBitmap>("d:\\sol.jpg")));
    }

    system("pause");
    _CrtDumpMemoryLeaks();
    return 0;
}

0 个答案:

没有答案