#include <iostream> #include <memory> // 需要包含此头文件 #include <vector> void example() { // 创建一个 std::shared_ptr 管理动态分配的 int 对象 std::shared_ptr<int> ptr1 = std::make_shared<int>(10); // 使用智能指针 std::cout << "Value: " << *ptr1 << std::endl; // ...
#include<iostream>#include<memory>intmain(){autop=std::shared_ptr<int>(newint(4));// int num{10};// auto p1 = std::shared_ptr<int>(p, &num);std::weak_ptr<int>wp1=p;autowp2=wp1;std::cout<<"wp1 use_count: "<<wp1.use_count()<<"\n"<<"p1: "<<*p<<"\n";return0;...
#include <memory> // 1.创建一个指向整型对象的unique_ptr,默认使用delete运算符释放资源 std::unique_ptr<int> uptr(new int(10)); // 2.C++ 14 使用 std::make_unique std::unique_ptr<int> uptr = std::make_unique<int>(10); std::unique_ptr<MyClass> uptr = std::make_unique<MyClass>(...
#include <iostream>using namespace std;class A{public: int Add(int a, int b);};int A::Add(int a, int b){returna + b;}intmain(){//std::shared_ptr<A>a=make_shared<A>();std::shared_ptr<A>a=std::shared_ptr<A>(new A());int res=a->Add(1,2);cout<<res<<endl;} 1....
#include <mutex> structTest { Test() { std::cout <<" Test::Test()\n"; } ~Test() { std::cout <<" Test::~Test()\n"; } }; //线程函数 voidthr(std::shared_ptr<Test> p) { //线程暂停1s std::this_thread::sleep_for(std::chrono::seconds(1)); ...
#include<memory>struct SomeType{voidDoSomething(){some_value++;}int some_value;};intmain(){std::shared_ptr<SomeType>ptr;ptr->DoSomething();return0;} 这里例子中,如果 ptr->DoSomething () 是运行在多线程中,讨论它是否线程安全,如何进行判断呢?
1include <iostream>2#include <memory>3#include <thread>4#include <chrono>5#include <mutex>67structTest8{9Test() { std::cout <<"Test::Test()\n"; }10~Test() { std::cout <<"Test::~Test()\n"; }11};1213//线程函数14voidthr(std::shared_ptr<Test>p)15{16//线程暂停1s17std::...
#include<iostream>class Node:public std::enable_shared_from_this<Node>{public:Node(conststd::string&name):name_(name){}~Node(){std::cout<<name_<<" destory"<<std::endl;}std::stringname()const{returnname_;}std::shared_ptr<Node>getSharePtr(){returnshared_from_this();}private:std::...
#include<iostream>#include<memory>usingnamespacestd;voiddelFun(string*p){cout<<"Fun delete "<<*p<<endl;deletep;}intmain(){cout<<"begin"<<endl;shared_ptr<string>pTom;{shared_ptr<string>pTom1(newstring("tom"),[](string*p){cout<<"Lamda delete "<<*p<<endl;deletep;});pTom=pTom1;...
#include <iostream> #include <memory> int main() { // 初始化一个std::shared_ptr std::shared_ptr<int> ptr1 = std::make_shared<int>(42); // 赋值操作 std::shared_ptr<int> ptr2 = ptr1; // 验证两个指针是否指向同一对象 if (ptr1.get() ==...