C++基础之分配动态内存allocator

C++编程中需要使用智能指针,而摒弃原始的指针,通过智能指针可以对指针对象(动态分配内存的对象)进行方便安全的操作;但是面对动态数组这种类型的数据,通过采用 new [],但C++ primer中使用了allocator进行分配动态数组,防止内存泄漏等问题。


#include <memory>
#include <iostream>
#include <string>

int main()
{
    std::allocator<int> a1;   // int 的默认分配器
    int* a = a1.allocate(1);  // 一个 int 的空间
    a1.construct(a, 7);       // 构造 int
    std::cout << a[0] << '\n';
    a1.deallocate(a, 1);      // 解分配一个 int 的空间

                              // string 的默认分配器
    std::allocator<std::string> a2;

    // 同上,但以 a1 的重绑定获取
    decltype(a1)::rebind<std::string>::other a2_1;

    // 同上,但通过 allocator_traits 由类型 a1 的重绑定获取
    std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;

    std::string* s = a2.allocate(2); // 2 个 string 的空间

    a2.construct(s, "foo");
    a2.construct(s + 1, "bar");

    std::cout << s[0] << ' ' << s[1] << '\n';

    a2.destroy(s);
    a2.destroy(s + 1);
    a2.deallocate(s, 2);

    getchar();
    return 0;
}
/*
7
foo bar
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值