天天看點

《Effective C++》筆記(一)

1,處理operator new記憶體配置設定失敗的情況

#include <iostream>

using namespace std;

template<typename T>    

class newhandlersupport 

{    //提供類set_new_handler支援的基類

public:

    static new_handler set_new_handler(new_handler p);

    static void* operator new(size_t size);//重載operator new運算符

private:

    static new_handler currenthandler;//目前的new_handler

};

template<typename T>

new_handler newhandlersupport<T>::set_new_handler(new_handler p)

{

    new_handler oldhandler = currenthandler;

    currenthandler = p;

    return oldhandler;

}

void* newhandlersupport<T>::operator new(size_t size)

    new_handler globalhandler = std::set_new_handler(currenthandler);//申請記憶體前先設定新的new_Handler

    void *memory;

    try 

    {

        memory = ::operator new(size);//實際配置設定記憶體

    }

    catch (std::bad_alloc&) 

        std::set_new_handler(globalhandler);//恢複舊的new_handler

        throw;//抛出異常

    std::set_new_handler(globalhandler);

    return memory;

new_handler newhandlersupport<T>::currenthandler = NULL;

class GamePlayer : public newhandlersupport<GamePlayer>

    static const int NUM_TURNS;

    int *scores;

    GamePlayer();

    ~GamePlayer();

const int GamePlayer::NUM_TURNS = 5;

GamePlayer::GamePlayer()

    cout<<"構造函數"<<endl;

    scores = new int[NUM_TURNS];

    memset(scores,0,sizeof(scores));

    for (int i =0;i<NUM_TURNS;++i)

        scores[i] = i;

GamePlayer::~GamePlayer()

    cout<<"析構函數"<<endl;

    for (int i=0;i<NUM_TURNS;++i)

        cout<<scores[i]<<'\t';

    cout<<endl;

    delete [] scores;

    scores = NULL;

void nomorememory()

    cerr << "unable to satisfy request for memory\n";

    abort();

int main()

{    

    ::set_new_handler(nomorememory);

    GamePlayer::set_new_handler(nomorememory);

    GamePlayer* pPlayOne = new GamePlayer();

    delete pPlayOne;

    GamePlayer::set_new_handler(NULL);

    try

        GamePlayer* pPlayTwo = new GamePlayer();

        delete pPlayTwo;

    catch (std::bad_alloc&)

        cerr<<"operator new failed"<<endl;

    system("pause");

    return 0;

本文轉自Phinecos(洞庭散人)部落格園部落格,原文連結:http://www.cnblogs.com/phinecos/archive/2008/04/15/1154258.html,如需轉載請自行聯系原作者

繼續閱讀