C++ STL memory.h 系列二

本文详细探讨了C++中的三种智能指针unique_ptr, shared_ptr和weak_ptr。从Effective Modern C++的条款出发,解释了它们的用法和注意事项,包括unique_ptr的移动构造函数、shared_ptr的引用计数以及weak_ptr在解决循环引用和内存泄漏中的作用。同时,提到了enable_shared_from_this的使用场景和原理。" 51142065,5005277,利用前序与中序遍历重建二叉树,"['二叉树算法', '递归算法', '数据结构', '华为面试题']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

智能指针

参考书录:Effective Modern C++ 第四章 智能指针

1. unique_ptr

条款18:使用unique_ptr管理具备专属所有权的资源

unique_ptr比auto_ptr更为高级,使用移动语义实现了原对象的置空,以下是一个例子:

class A {
public:
    A() {}
    A(const A&) = delete;
    A(A&&) { std::cout << "move construction" << std::endl; }
};

A makeA() { A a; return a; }

int main()
{
    
    auto a = makeA();

    return 0;
}

其输出为:

move construction

使用移动构造函数可以使得临时变量被转移至函数体外而不析构,以下为以unique_ptr为例子的工厂函数。若析构器是函数指针,那么unique_ptr的尺寸一般会增加一到两个字长。若为函数对象则取决于其中存储多少状态。无状态的函数对象(例如,无捕获的lambda表达式)不会浪费任何存储尺寸。

auto delInvmt = [](Investment* inv) {
    inv->logging();
    delete inv;
};

template<typename ...Args>
tinySTL::unique_ptr<Investment, decltype(delInvmt)>
makeInvestment(INVTYPE type, Args&&... args) {
    tinySTL::unique_ptr<Investment, decltype(delInvmt)>
        pInv(nullptr, delInvmt);
    if (type == INVTYPE::STOCK) {
        pInv.reset(new Stock(tinySTL::forward<Args>(args)...));
    }
    else if (type == INVTYPE::BOND) {
        pInv.reset(new Bond(tinySTL::forward<Args>(args)...));
    }
    else if (type == INVTYPE::REALESTATE) {
        pInv.reset(new RealEstate(tinySTL::forward<Args>(args)...));
    }

    return pInv;
}

这里有一个问题,就是当delInv为函数对象时出现“类模板的成员无法获取函数类型”问题。这是函数指针和函数对象类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值