俊's profile俊俊的共享空间PhotosBlogLists Tools Help

Blog


    March 03

    new的处理方式(粗糙)

    new_handler X::currentHandler; // 缺省设置currentHandler 0(null)

     

    X 中的set_new_handler 函数会保存传给它的任何指针,并返回在调用

    它之前所保存的任何指针。这正是标准版本的set_new_handler 所做的:

     

    new_handler  X::set_new_handler(new_handler p)

    {

    new_handler oldHandler = currentHandler;

    currentHandler = p;

    return oldHandler;

    }

     

    全局跟类中一样的方式,类静态数据成员变成全局成员而已。

     

    非类成员形式的operator new 的伪代码看起来会象下面这样:

    void * operator new(size_t size) // operator new 还可能有其它参数

    {

    if (size == 0) { // 处理0 字节请求时,

    size = 1; // 把它当作1 个字节请求来处理

    }

    while (1) {

    分配size 字节内存;

    if (分配成功)

    return (指向内存的指针);

    // 分配不成功,找出当前出错处理函数

    new_handler globalHandler = set_new_handler(0);

    set_new_handler(globalHandler);

    if (globalHandler) (*globalHandler)();

    else throw std::bad_alloc();

    }

    }

     

    成员形式的operator new 的伪代码看起来会象下面这样:

    void * X::operator new(size_t size)

    {

    new_handler globalHandler = // 安装X new_handler

    std::set_new_handler(currentHandler);

    void *memory;

    try { // 尝试分配内存

    memory = ::operator new(size);

    }

    catch (std::bad_alloc&) { // 恢复旧的new_handler

    std::set_new_handler(globalHandler);

    throw; // 抛出异常

    }

    std::set_new_handler(globalHandler); // 恢复旧的new_handler

    return memory;

    }

    Comments (2)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    专业路过……
    大家要小心,此人对C++的底层实现技术有狂热的探究精神……
     
    被称为“C++的盗墓者”……
    Mar. 5
    hq jiangwrote:
    专业
    Mar. 3

    Trackbacks

    The trackback URL for this entry is:
    http://iuq-qj.spaces.live.com/blog/cns!4138B0A9810421A4!214.trak
    Weblogs that reference this entry
    • None