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

  • 相关阅读:
    Window 服务安装
    SQL
    vb To c# or c# To vb
    CacheHelper-缓存
    让Linq的OrderBy支持动态字段
    哪些列上适合建立索引???
    如何查看Oracle数据库中无效的对象,约束,触发器和索引
    如何查看Oracle中被锁定的表
    ORACLE ASM
    WebLogic Server
  • 原文地址:https://www.cnblogs.com/judes/p/11091416.html
Copyright © 2011-2022 走看看