This class is very interesting, so that a class managed by shared_ptr can access shared_ptr within its own member function. It's a bit difficult.
For example, the following code constructs a shared_ptr object through this in function f, and then prints the value of x.
[Cpp]
Class B {
Public:
B (): x _ (4 ){
Cout <"B: B ()" <endl;
}
~ B (){
Cout <"B ::~ B () "<endl;
}
Void f (){
Shared_ptr <B> p (this );
Cout <p-> x _ <endl;
// Shared_from_this ();
}
Private:
Int x _;
};
/*
*
*/
Int main (int argc, char ** argv ){
Shared_ptr <B> x (new B );
X-> f ();
Return 0;
}
The compilation is successful, but the running result is:
[Cpp]
B: B ()
4
B ::~ B ()
B ::~ B ()
It is a disaster to analyze the object B twice.
Now try enable_shared_from_this:
[Cpp]
Class A: public enable_shared_from_this <A> {
Public:
A (){
Cout <"A: A ()" <endl;
}
~ A (){
Cout <"::~ A () "<endl;
}
Void f (){
// Cout <shared_from_this ()-> x _ <endl; // this way is okay too
Shared_ptr <A> p = shared_from_this ();
Cout <p-> x _ <endl;
}
Private:
Int x _;
};
/*
*
*/
Int main (int argc, char ** argv ){
Shared_ptr <A> x (new );
X-> f ();
Return 0;
}
Running result:
[Cpp]
A: ()
0
A ::~ A ()
So why do we need to do this? Accessing your own members in your own class is actually just a sample code, and it is not necessary.
However, there is a possibility that the f function needs to return its own pointer to the caller. Is it written like this?
[Cpp]
A * f ();
A bare pointer is returned and out of control. No one knows what the caller will do?
The clever method is to design it as follows:
Shared_ptr <A> f ()
Okay, that's why we need enable_shared_from_this.