Making your C++ code robust

  • Using Smart Pointers

       如果你经常使用用享对象指针,如COM 接口等,那么建议使用智能指针来处理。智能指针会自动帮助你维护对象引用记数,并且保证你不会访问到被删除的对象。这样,不需要关心和控制接口的生命周期。关于智能指针的进一步知识可以看看Smart Pointers - What, Why, Which? 和 Implementing a Simple Smart Pointer in C++这两篇文章。

       如面是一个展示使用ATL's CComPtr template 智能指针的代码,该部分代码来至于MSDN。

#include <windows.h>
#include <shobjidl.h> 
#include <atlbase.h> // Contains the declaration of CComPtr.
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | 
        COINIT_DISABLE_OLE1DDE);
    if (SUCCEEDED(hr))
    {
        CComPtr<IFileOpenDialog> pFileOpen;
        // Create the FileOpenDialog object.
        hr = pFileOpen.CoCreateInstance(__uuidof(FileOpenDialog));
        if (SUCCEEDED(hr))
        {
            // Show the Open dialog box.
            hr = pFileOpen->Show(NULL);
            // Get the file name from the dialog box.
            if (SUCCEEDED(hr))
            {
                CComPtr<IShellItem> pItem;
                hr = pFileOpen->GetResult(&pItem);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszFilePath;
                    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
                    // Display the file name to the user.
                    if (SUCCEEDED(hr))
                    {
                        MessageBox(NULL, pszFilePath, L"File Path", MB_OK);
                        CoTaskMemFree(pszFilePath);
                    }
                }
                // pItem goes out of scope.
            }
            // pFileOpen goes out of scope.
        }
        CoUninitialize();
    }
    return 0;
}  

  • Using == Operator Carefully

       先来看看如下代码;

  CVehicle* pVehicle = GetCurrentVehicle();
   
  // Validate pointer
  if(pVehicle==NULL) // Using == operator to compare pointer with NULL
     return FALSE; 
 
  // Do something with the pointer
  pVehicle->Run();

 上面的代码是正确的,用语指针检测。但是如果不小心用“=”替换了“==”,如下代码;

 CVehicle* pVehicle = GetCurrentVehicle();
 
  // Validate pointer
  if(pVehicle=NULL) // Oops! A mistyping here!
     return FALSE; 
 
  // Do something with the pointer
  pVehicle->Run(); // Crash!!! 

看看上面的代码,这个的一个失误将导致程序崩溃。

       这样的错误是可以避免的,只需要将等号左右两边交换一下就可以了。如果在修改代码的时候,你不小心产生这种失误,这个错误在程序编译的时候将被检测出来。

你可能感兴趣的:(Making your C++ code robust)