The COM interface pointer is very dangerous, because every user must strictly and correctly address and release during use. Once a problem occurs, the object cannot be released normally, or the object is deleted repeatedly, resulting inProgramCrash. Therefore, you must be careful when using the COM interface.
However, even if allCodeAre correct addref and release, and it cannot be guaranteed. For example:
Void someapp (ihello * phello)
{
Ihello * pcopy = phello;
Pcopy-> addref ();
Otherapp ();
Pcopy-> Hello ();
Pcopy-> release ();
}
It seems impeccable, but if an exception is thrown in the otherapp, Will pcopy-> release be skipped?
Fortunately, all the problems are from simple to complex, and then from complicated to simple, because we have ccomptr!
ccomptr is called a smart pointer and is a template class provided by ATL. It can automatically complete addref and release in syntax. ( Source Code In atlbase. h)
the usage of ccomptr is very simple. Taking ihello * as an example, all interface pointer types (except parameters) in the program are replaced by ccomptr . That is to say, in addition to parameters in the program, do not use ihello *, all of which are replaced by ccomptr .
the usage of ccomptr is almost the same as that of common com pointers. Note the following when using ccomptr.
1. ccomptr ensures that addref and release are called correctly. Therefore, you do not need to call addref and release.
2. If you want to release a smart pointer, just assign it a null value.
3. the com pointer is released when the ccomptr destructor is created.
4. When using the & operator for ccomptr (getting pointer addresses), make sure that ccomptr is NUL. (Because addref is not automatically called when ccomptr is assigned a value through the ccomptr address. If it is not null, the previous pointer cannot be released, and ccomptr will use assert for alarm)
take the program as an example:
void someapp (ihello * phello)
{< br> ccomptr pcopy = phello;
otherapp ();
pcopy-> Hello ();
}< br> because pcopy is a local object, even if otherapp () throws an exception, pcopy will also be destructed, And the pointer can be released.
if you do not want to crash the com pointer reference count before the program is about to be released, keep this in mind: In addition to parameters, do not directly use the com pointer type. You must replace all with ccomptr .