5. Object Life Management System
/ / The first parameter interface class, the second parameter specific class
Template
Class SIP {
PUBLIC:
// Mapping from an interface of the implementation to another interface
Template
SIP
{
Return Sip
}
Explicit
/ / Mapping to the intelligent interface pointer from a specific class that already exists (band-constructed)
SIP (C * C): _ c (c) {
_i = static_cast (c);
_i-> addref ();
}
// No argument, the case where the specific class does not have a constructor
Explicit
SIP (): {
_C = new C;
_i = static_cast
_i-> addref ();
}
SIP (SIP & p) {// cctor
_i = p.get ();
_c = p.get2 ();
_i-> addref ();
COUT << "cctor" << endl;
COUT << _ i-> ct ();
}
SIP & operator = (SIP & p)
{
_i = p.get ();
_c = p.get2 ();
_i-> addref ();
COUT << "Operator =" << endl;
COUT << _ i-> ct ();
}
I & operator * () const
{// return designated value
Return (* _i);
}
I * operator -> () const
{// Return Pointer to Class Object
Return (& ** this);
}
I * get () const
{// return wrapped pointer
Return (_i);
}
C * Get2 () const
{// return wrapped pointer
Return (_C);
}
~ SIP ()
{
_i-> release ();
}
Private:
I * _i; // interface pointer
C * _c; // specific class pointer
}
Template
SIP Cast (C * C)
{
RETURN SIP (C);
}
Interface iunknown {
Virtual Int AddRef (Void) = 0;
Virtual Int release (void) = 0;
}
#define declare_iunknown () /
PUBLIC: /
Virtual Int Addref (Void) /
{/
Count ; /
Return 0; /
}; /
Virtual Int Release (Void) /
{/
Count -; /
IF (count == 0) {/
DELETE THIS; /
} /
Return 0; /
}; /
PUBLIC: /
INT country;
Main.cpp # include "stdafx.h"
#include "global_datastruct.h"
#include "SENTENCEMANAGER.H"
Using namespace std;
Typedef Sip
PisentenceManager A ()
{
CsentenceManager * ps = new csenceptencyManager; // Specific class with constructor (pointer)
PisentenceManager P = CAST
COUT << "CT:";
COUT << PS-> count;
Return PisentenceManager (P); // Construct a temporary SIP
}
Void B ()
{
PisentenceManager P (A ()); // Construct a new SIP with a temporary SIP
PisentenceManager P2 = P; // Assign another SIP with another SIP
COUT << "CT:";
COUT << P-> CT ();
P2-> display_the_sentence ();
// Interface map, one interface in the SIP containing an interface, map to another interface supported by the object
TypeDef Sip
PI2 PP = P.cast
COUT << "CT:";
PP-> show ();
}
INT _Tmain (int Argc, _tchar * argv [])
{
b ();
INT X;
CIN >> X;
Return 0;
}
Output:
CT: 1Copy Construct
2Copy Construct
2CT: 2DO SHMEYING ON CSENTENCEMANAGER
0012FCD4
CT: T2
CT: 0
Destoried