This should start with a smart pointer. A smart pointer is to dynamically manage a pointer using the construction and destructor of a variable. To put it bluntly, construct -- new; destructor -- delete. We can easily write a smart pointer: templateclassTclassTAutoPtr {public: TAutoPtr () {m_tnewT (); coutTAutoPtr: TAutoPt
This should start with a smart pointer. A smart pointer is to dynamically manage a pointer using the construction and destructor of a variable. To put it bluntly, construct -- new; destructor -- delete. We can easily write a smart pointer: template class Tclass TAutoPtr {public: TAutoPtr () {m_t = new T (); cout TAutoPtr: TAutoPt
This should start with a smart pointer. A smart pointer is to dynamically manage a pointer using the construction and destructor of a variable.
To put it bluntly, construct --> new; destructor --> delete
We can easily write a smart pointer:
template
class TAutoPtr{public: TAutoPtr() { m_t = new T(); cout << "TAutoPtr::TAutoPtr()" << endl; } ~TAutoPtr() { delete m_t; cout << "TAutoPtr::~TAutoPtr()" << endl; }private: T* m_t;};
Usage:
int main(int argc, char** argv){ TAutoPtr
tt; return 0;}
This is okay.
Boost: asio provides this method, allowing shared_ptr to quickly manage your class.
However, this causes a problem. When your class is derived from enable_shared_from_this, you cannot use shared_from_this () in the class member function to obtain class pointers.
The following is an error:
class B { public: B(): x_(4) { cout << "B::B()" << endl; } ~B() { cout << "B::~B()" << endl; } void f() { shared_ptr p(this); cout << p->x_ << endl; } private: int x_; }; int main(int argc, char** argv) { shared_ptr x(new B); x->f(); return 0; }
Output:B: B ()
4
B ::~ B ()
B ::~ B ()
The same object is analyzed twice, causing catastrophic consequences.
Similarly, the following usage is also incorrect:
class A : public enable_shared_from_this { public: A() { cout << "A::A()" << endl; } ~A() { cout << "A::~A()" << endl; } void f() { //cout << shared_from_this()->x_ << endl; // this way is okay too shared_from_this(); //shared_ptr p = shared_from_this(); //cout << p->x_ << endl; }private: int x_;};int main(int argc, char** argv){ A* aa = new A(); aa->f(); return 0;}
Although we have sent the Class A to enable_shared_from_this, shared_ptr Class A is not used. It is also incorrect.
Summary:
1. This class is derived from enable_shared_from_this. Example: class A: public enable_shared_from_this
2. shared_ptr abc (new A () must be added for use ())