Some suggestions for smart pointers in COM.

zhaozj2021-02-08  224

Be careful when using the smart pointer CComptr and CCOMQIPTR with the ATL. The following code assumes that there is a component TestComptr, and the CLSID of its component is CLSID_TESTComptr, exposes an interface ITESTCompTR to the customer. int main () {HRESULT l_hr; CoInitialize (NULL); CComPtr l_spTestCOMPtr; l_hr = l_spTestCOMPtr.CreateInstance (CLSID_ TESTCOMPtr); if (FAILED (l_hr)) {return l_hr;} // dosomething of ITestCOMPtr CoUninitialize (); } There is no problem with this code, but it will still collapse. If we are in Coinitialize (NULL); add "{" and Couninitialize (); uplink plus "}" will not have an error. why? The reason is that the set of Coinitialize is in Couninitialize (); it has been closed. The component object of the smart pointer is not released until the programmatic function of the program calls ccComptr , the Release method of ITESTComptr is called, but at this time, the socket is already, so that the program's crash is caused. When the life cycle of the component is very short, the use of the smart pointer is basically harmless and sometimes very convenient.

So there is a suggestion when using a smart pointer: 1. Be careful when the life cycle of the object is very long. 2. Do not use when the life cycle of the object is uncertain. 3. Don't use the global intelligent pointer.

转载请注明原文地址:https://www.9cbs.com/read-2794.html

New Post(0)