《C++ Primer》第19章 19.1节习题答案

《C++ Primer》第19章 特殊工具与技术

导读

本章介绍了一些特殊的C++特性,如控制内存分配、运行时类型识别、枚举类型等。

本章的练习通过贯穿本书的一些例子帮助读者练习这些语言特性的使用。

19.1节习题答案

练习19.1:使用malloc编写你自己的operator new(size_t)函数,使用free编写operator delete(void *)函数。

【出题思路】

用户自定义operator new函数和operator delete函数的练习,控制内存分配的过程,不局限于标准库中定义的版本。

【解答】

#include <iostream>
#include <cstdlib>
#include <new>

using namespace std;

void *operator new(size_t size)
{
    cout << "size=============" << size << endl;
    if(void *mem = malloc(size))
    {
        return mem;
    }
    else
    {
        throw bad_alloc();
    }
}

//编译时必须指定C++11,否则noexcept会导致编译错误
void operator delete(void *mem) noexcept
{
    cout << "mem=============" << mem << endl;
    free(mem);
}

int main()
{
    int *n1 = new int(20);
    cout << "n1=============" << *n1 << endl;
    int *n2 = new int;
    cout << "n2=============" << *n2 << endl;
    delete n1;
    delete n2;
    cout << "Hello World!" << endl;
    return 0;
}

运行结果:

 

练习19.2:默认情况下,allocator类使用operator new获取存储空间,然后使用operator delete释放它。利用上一题中的两个函数重新编译并运行你的StrVec程序(参见13.5节,第465页)。

【出题思路】

使用自定义的全局operator new和operator delete函数执行分配内存和释放内存的操作,测试其分配内存的方式是否与标准方式类似。

【解答】

在分配新空间时

T *newelements = alloc.allocate(newcapacity);

可以重写为:

T *newelements = static_cast<T *>(operator new[](newcapacity * sizeof(T)));

类似的,在重新分配由Vector成员elements指向的旧空间时

alloc.deallocate(elements, end - elements);

可以重写为:

operator delete[](elements);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值