// 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