shared_ptr and weak_ptr

The sample code to show the key difference.

 

#include <tr1/memory>
#include <iostream>
using namespace std;

class Strong {
  public:
    ~Strong() {
      cout << "destroy Strong\n";
    }
    tr1::shared_ptr<Strong> m_cycle;
};

class Weak {
  public:
    ~Weak() {
      cout << "destroy Weak\n";
    }
    tr1::weak_ptr<Weak> m_cycle;
};

int main() {
  // the `Strong' object created above is now leaked!
  {
    tr1::shared_ptr<Strong> p(new Foo);
    p->m_cycle = p;
  }

  // the 'Weak' object created above is released!
  {
    tr1::shared_ptr<Weak> shared(new Weak); 
    shared->m_cycle = shared;
  }
  return 0;
}
 

 

你可能感兴趣的:(weak)