1、如果写自己的new、delete操作符,则标准做法为
class Widget
{
public:
void *operator new(size_t);
void operator delete(void *, size_t);
void *operator new[](size_t n)
{
return ::operator new[](n);
}
void operator delete[](void *p, size_t);
{
::operator delete[](p);
}
//.....................................
};
2、new不成功则抛bad_alloc异常,不过可以通过int *i = new(nothrow) int;来阻止异常,
出错时返回null;
3、相对vc6,在vc7的afxdb.h对CDBVariant添加了DBVT_ASTRING和DBVT_WSTRING两种类型(使用MFC ODBC类来访问数据库);
4、中括号
听说这样的程序用Gcc可以跑得过,
void main()
try
{
}
catch(...)
{
}
当时觉得没什么意思,也没去深想,但是刚刚有空试了一下,在VC6下是不可以的,在vc7
就OK。看来确实是C++标准。再试下这个
void fn()
try
{
}
catch(...)
{
}
void main(){}
也是OK的,看来这个try,catch结构可以限定函数的范围,而bool fn() return true;是不可以的。
再进一步:
#include <exception>
int f()
{
while(1)
try
{
throw exception();
}
catch (exception &)
{
return true;
}
}
void main()
{
}
这也是没有问题的。所以联想到switch也可以的,结果也试过确实是这样。其它的if、while就不行了。
5、关于CMemFile,尽管开始使用时没有attach,但最好在最后手动detach和delete;
6、union妙用:下面程序是用来接受内存块的大小(用4个字节表示)
union
{
long nBlockSize;
char BlockSize[sizeof(long)];
} block;
// Receive the header of the block
int nReadCnt = 0;
while(nReadCnt < sizeof(long))
{
int CurLen = m_pSocket->Read( (block.BlockSize+nReadCnt), sizeof(long)-nReadCnt );
if (CurLen < 0)
throw(Exception(RETCODE_ERROR,"接收内存文件: 无法读缓冲区长度: %d",CurLen));
nReadCnt += CurLen;
}
lBlockSize = ntohl( block.nBlockSize );
想想,可能是自己看别人写的代码量太少了,以后还是得多接触开源项目,接受熏陶:)
另外借了《程序设计实践》和《编写安全代码》两书,lucky!!