std::shared_ptr<int> p7(new int[10], deleteInt); 四shared_ptr常用函数 get()函数,表示返回当前存储的指针(就是被shared_ptr所管理的指针) 。 但是不建议使用get()函数获取 shared_ptr 关联的原始指针,因为如果在 shared_ptr 析构之前手动调用了delete函数,会导致错误 shared_ptr<T> ptr(new T()); ...
#include<iostream>#include<string>#include<memory>usingnamespacestd;intmain() {int len =128;shared_ptr<char>ptr(newchar[len]);// 得到指针的原始地址char* add = ptr.get();memset(add,0, len);strcpy(add,"博客:进击的汪sir");cout <<"string: " << add <<endl;shared_ptr<int>p(newint...
shared_ptr<T>ptr(newT);// T可以是int、char、class等各种类型shared_ptr<std::string>sps(newstd::string("smart"));// 一个string的shared_ptrassert(sps->size() ==5);// 使用箭头操作符->shared_ptr<int>dont_do_this(newint[10]);// 错误用法,不能正确释放内存 增加计数 被引用会增加计数 ...
1. 先看std::shared_ptr<T> 基本使用(也看看怎么解决循环引用) A:std::shared_ptr<T>的使用场景分析 A-1:当资源共享时,怎么使用std::shared_ptr<T> 呢? A-2:std::shared_ptr 在循环引用的场景下使用 A-3:分析(为什么std::weak_ptr可以解决std::shared_ptr的循环引用问题呢?) A-4:凡事都有风险(...
#include<iostream>#include<memory>intmain(){auto*p=newstd::string("hello");std::shared_ptr<std::string>sp1(p);/*不要这样做!!*/std::shared_ptr<std::string>sp2(p);return0;} 这样会导致两个shared_ptr管理同一个对象,当其中一个被销毁时,其管理的对象会被销毁,而另外一个销毁时,对象会二次...
std::shared_ptr 和普通指针的转换 普通指针和std::shared_ptr相互转化见示例 struct test { int num; string name; }; test* pTest = new test(); std::shared_ptr<test> ptr_test = std::shared_ptr<test>(pTest); //普通指针转shared_ptr...
shared_ptr是线程安全的吗? 请看下面一段代码 代码语言: 代码运行次数:0 #include<stdio.h>#include<iostream>#include<string.h>#include<memory>#include<mutex>#include<thread>using namespace std;shared_ptr<long>global_instance=make_shared<long>(0);std::mutex g_i_mutex;voidthread_fcn(){//std:...
虽然我们借shared_ptr 来实现线程安全的对象释放,但是shared_ptr 本身不是100% 线程安全的。它的引用计数本身是安全且无锁的,但对象的读写则不是,因为shared_ptr 有两个数据成员,读写操作不能原子化。根据文档11,shared_ptr 的线程安全级别和内建类型、标准库容器、std::string 一样,即: ...
void worker(std::shared_ptr<int> ptr) { std::shared_ptr<int> loaded_ptr = std::atomic_load(&ptr); std::cout << "Loaded value: " << *loaded_ptr << std::endl; } int main() { std::shared_ptr<int> ptr = std::make_shared<int>(42); ...
在c++ 98 里面只有一种智能指针,就是 std::auto_ptr,因为具有唯一所有权的特征,所以限制了它的使用范围,比如你无法在容器中使用它。而我们知道 stl 容器是值语义的,如果不能用智能指针管理的话,只有两种办法来使用。 一种是类似这样: std::vector<std::string> names; ...