c++ shared_ptr

void f(shared_ptr<int>, int);
int g();

void ok()
{
    shared_ptr<int> p( new int(2) );
    f( p, g() );
}

void bad()
{
    f( shared_ptr<int>( new int(2) ), g() );
}

shared_ptr

#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
using std::cout;
using std::endl;
struct Base
{
    Base() {
        cout << "Base::Base()\n";
    }
    ~Base() {
        cout << "Base::~Base()\n";
    }
};


struct Derived :public Base {
    Derived() {
        cout << "Derived::Derived()" << endl;
    }
    ~Derived() {
        cout << "Dervive::~Derived()" << endl;
    }

};

void thr(std::shared_ptr<Base> p) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::shared_ptr<Base> lp = p;
    {
        static std::mutex io_mutex;
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << "local pointer in a thread:\n"
            << "lp.get()" << lp.get()
            << ",lp.use_count()" << lp.use_count() << "\n";
    }

}
int main() {
    std::shared_ptr<Base> p = std::make_shared<Derived>();
    std::cout << "Created a shared Derived (as a pointer to Base)\n"
        << "p.get" << p.get()
        << ",p.use_count()= " << p.use_count() << "\n";
    std::thread t1(thr, p), t2(thr, p), t3(thr, p);
    p.reset(); // release ownership from main
    std::cout << "shared ownership between 3 threads and released\n"
        << "ownership from main:\n"
        << "p.get()" << p.get()
        << ",p.use_count()" << p.use_count() << "\n";
    t1.join(); t2.join(); t3.join();
    std::cout << "All threads completed,the lase one deleted Derived\n";
    system("pause");
    return 0;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 本文版權歸 liancheng 所有,如有轉載請按如下方式標明原創作者及出處,以示尊重!!原創作者:lianche...
    周肅閱讀 7,703評論 2 6
  • 原作者:Babu_Abdulsalam 本文翻譯自CodeProject,轉載請注明出處。 引入### Ooops...
    卡巴拉的樹閱讀 30,178評論 13 74
  • 導讀## 最近在補看《C++ Primer Plus》第六版,這的確是本好書,其中關于智能指針的章節解析的非常清晰...
    小敏紙閱讀 2,021評論 1 12
  • 專屬所有權:unique_ptr 我們大多數場景下用到的應該都是 unique_ptr。 unique_ptr 代...
    wayyyy閱讀 1,240評論 0 1
  • malloc/free malloc/free are management methods of memory ...
    auguszou閱讀 565評論 0 1