01. Never allocate memory like this way
void MyFunc(CString strText)
{
int size = strText.GetLength();
TCHAR* pszNewText = new TCHAR[size];
// Good practice is: TCHAR* pszNewText = new TCHAR[size+1];
}
02. Never just delete memory say delete pMyObj, always set pMyObj = NULL after delete
03. Although it doesn't make much difference, but always use the [] operator after using delete for arrays.
Example:
// Always better to use [] after delete for array of any sort of datatypes
delete[] myarray;
04. Avoid Using In/Out Parameters.
That is Avoid using the same parameter as Input as well as output parameter.
Example:
Bad code:
BOOL GetMergedCellRect(CRect& rect)
{
rect.top++;
rect.bottom--;
Return TRUE;
}
Good Code:
BOOL GetMergedCellRect(CRect rect, /*OUT*/CRect& mergedRect)
{
mergedRect = rect;
mergedRect.top++;
mergedRect.bottom--;
}
Although if u have a method such as InflateRect, DeflateRect, whose names are obviously and clearly stating you to do some operation on the passed rectangle, in those cases you can off course use the same parameter as input and output.
05. I think it would be a good idea to typedef the parent class as Super inside the child class.
Example:
class wxEdit : public wxWindow
{
typedef wxWindow Super;
public:
void OnPaint()
{
Super::OnPaint();
}
}
This technique is used in Symbian OS.
06. Although we did some ugly hacking because of the circumstances, but the following is not acceptable. You cannot allow your base class to know about your child classes,
For example, you should never declare a child class a friend of your base class unless absolutely necessary.
class CHotListCtrlCellBase : public CObject
{
friend class CHotListCtrlURLCell;
friend class CHotListCtrlCellCombo;
friend class CHotListCtrlCellCheck;
...
};
06. All of us may be confused or do mistake while using memset() function.
Here is an example that shows correct way of using memset():
TCHAR* pBuff = new TCHAR[256];
memset( pBuff, 0, 256);

No comments:
Post a Comment