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();

}

猜你喜欢

转载自blog.csdn.net/wyg_031113/article/details/128300497