c++11-智能指针-std::function-std::bind

本文深入探讨C++中智能指针的概念,包括shared_ptr, weak_ptr及unique_ptr的不同应用场景,以及如何使用std::function和std::bind进行函数绑定。通过实例展示在多线程环境下智能指针和函数绑定的正确使用方法。

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

在线帮助手册 https://zh.cppreference.com/w/cpp

智能指针
share_ptr 、weak_ptr、unique_ptr
share_ptr 掌控声明周期,和引用计数
weak_ptr 如果有对象有引用计数则可管理,没有就算了。
他们适用的场合也不同,第二种适用于例如系统提供的对象,或者第三方提供的,我要用但是我不能完全的掌控他的关闭可开启;

std::function

std:bind

#include <iostream>
#include <thread>
#include <mutex>

class A{
public:
    A() { }
    ~A() {}
    int x;
};
void threadPor(A a)
{
    std::cout << a.x << std::endl;
}
int main()
{
   A a;
   a.x = 1;
   
   auto th = new std::thread(std::bind(&threadPor,a),1);
   th->join();
   delete th;
   system("pause");
   return 0;
}

bind 一些注意事项:
A 类中如果有堆区数据,要 ----深拷贝。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值