VirtualAlloc系のアロケータクラス (CVirtualAllocator) [ATL]

(2007.05.16)
#pragma once
 
// WAC.com Class Liblary for Visual C++
// Copyright (C) WAC.com Inc. All rights reserved.
//
// This file is a part of the WAC.com Class Liblary.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.TXT at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license. You must not remove this notice, or
// any other, from this software.
 
// '04.03.24 : 新規作成 (sha)
// '06.04.14 : CVirtualAllocator::Reallocate() の修正 (sug)
// '07.03.20 : CVirtualAllocator::VirtualFreeのNULLチェック(AppVerifier対応)(imatsu)
// '07.04.06 : コードの整備 (sha)
// '07.05.16 : Reallocateの仕様を、VC8に準拠 (sha)
 
 
////////////////////////////////////////////////////////////////////////////////
// CVirtualAllocator
 
class CVirtualAllocator
{
public:
    static void* Allocate(size_t nBytes) throw()
    {
        return ::VirtualAlloc(NULL, nBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); 
    }
    static void* Reallocate(void* p, size_t nBytes) throw()
    {
#if (_MSC_VER >= 1400) // VS2005
        if (p==NULL){
            return ( Allocate(nBytes) );
        
        }
        if (nBytes==0){
            Free(p);
            return NULL;
        }
#endif
 
        void* pNew = ::VirtualAlloc(NULL, nBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); 
        if (pNew)
        {
            size_t nOrgBytes = CVirtualAllocator::GetSize(p);
            size_t nCopySize = (nBytes >= nOrgBytes) ? nOrgBytes : nBytes;
            ::MoveMemory(pNew, p, nCopySize);
        }
 
        if (p)
        {
            ::VirtualFree(p, 0, MEM_RELEASE);
        }
 
        return pNew;
    }
    static void Free(void* p) throw()
    {
        if (p)
        {
            ::VirtualFree(p, 0, MEM_RELEASE);
        }
    }
 
public:
    static size_t GetSize(void* p) throw()
    {
        MEMORY_BASIC_INFORMATION pbi = { 0 };
        ::VirtualQuery(p, &pbi, sizeof(pbi));
        
        return pbi.RegionSize;
    }
};
一覧に戻る
© 2003 WAC.com All Right Reserved.