c++ shared_ptr

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

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

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

shared_ptr

#include 
#include 
#include 
#include 
#include 
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 p) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::shared_ptr lp = p;
    {
        static std::mutex io_mutex;
        std::lock_guard 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 p = std::make_shared();
    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;
}

你可能感兴趣的:(c++ shared_ptr)