C++20奇异模板递归:enable_shared_from_this shared_ptr/unique_ptr/weak_ptr

#include <iostream>
#include "common/log.h"
#include <limits>
#include <vector>
#include <span>
#include <array>
#include <type_traits>
#include <cmath>
#include <memory>
#include <variant>
using namespace AdsonLib;
struct Point{
    int x;
    int y;
};

struct Shape : public std::enable_shared_from_this<Shape>{
    int w;
    int h;
    auto ShareMe(){
        return shared_from_this();
    }
    auto WeakMe(){
        return weak_from_this();
    }
};

int main(int argc, char *argv[]) {
    //shared_ptr要传递给很多函数,很多类中使用
    //效率低,因为要申请两次动态内存分别给shared_ptr控制块和Point
    std::shared_ptr<Point> p(new Point{1,2});
    //效率高,一次内存申请,控制块放在内存头部
    auto p2 = std::make_shared<Point>(1,2);

    //弱指针,不增加引用计数,解决循环依赖问题,通过Loca获取shared_ptr
    std::weak_ptr<Point> w(p);
    LOG(INFO) << "weak: expired: " << w.expired() << " use_count:" << w.use_count() << " lock: " << w.lock().use_count();

    //不能共享,只能通过std::move(p3)来移动。在类内成员或者函数里用这个。不用开辟控制块,开销小
    auto p3 = std::make_unique<Point>(3,4);

    auto s1 = std::make_shared<Shape>();
    auto s2 = s1->ShareMe();
    auto s3 = s2->WeakMe();
    LOG(INFO) << "share: " << s1.get() << " " << s2.get() << " " << s3.lock().use_count();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值