zoukankan      html  css  js  c++  java
  • shared_ptr智能指针

    // Test.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <thread>
    #include <memory>
    #include <iostream>
    #include <assert.h>
    #include <thread>
    #include<windows.h>
    
    
    #define OPEN_IF 1
    #define CLOSE_IF 0

    class B { public: B() { std::cout << "B Create" << std::endl; } ~B() { std::cout << "B Destroy" << std::endl; } void fun() { std::cout << "B fun" << std::endl; } private: }; void threadFun(std::shared_ptr<B> ptr) { int count = 5; auto source = ptr.get(); std::cout << "thread ptr:" << ptr << std::endl; #if CLOSE_IF std::cout << "source address:" << source << std::endl; std::cout << "current thread id:" << GetCurrentThreadId() << std::endl; #endif while (count--) { ptr->fun(); Sleep(1000); } ptr.reset(); std::cout << "B after use count:" << ptr.use_count() << std::endl; } int main() { B *b = new B(); std::shared_ptr<B> myPtr1(b); std::cout << "source ptr:" << myPtr1 << std::endl; std::thread threadA(threadFun, myPtr1); std::cout << "B before use count:" << myPtr1.use_count() << std::endl; threadA.detach(); myPtr1.reset(); getchar(); return 0; }

    注意:shared_ptr作为参数【函数参数、线程参数】时,不管是不是引用传递,都是拷贝复制,所以它们的计数器是同一个,所以计数+1

  • 相关阅读:
    js高级1
    JUC总览
    7 种阻塞队列相关整理
    Exchanger 相关整理
    Semaphore 相关整理
    ConcurrentLinkedQueue 相关整理
    ConcurrentHashMap(1.8) 相关整理
    ConcurrentHashMap(1.7) 相关整理
    ReentrantReadWriteLock 相关整理
    LockSupport 工具相关整理
  • 原文地址:https://www.cnblogs.com/judes/p/11091416.html
Copyright © 2011-2022 走看看