1.CTypedPtrList<CObList, CDrawObj*> 與 std::vector<CDrawObj*>
如果CDrawObj*從COject繼承用CTypedPtrList優(yōu)于用std::vector,雖然std::vector很優(yōu)美,但在
MFC下,MFC類是大房,std::vector是小妾,很多MFC類的功能std::vector用不了,CTypedPtrList可以.
比如直接的容器序列化,如果使用std::vector的話,你的工作將很多,保存時需遍歷對象,一個一個保存,讀取時你要知道對象的具體類型(繼承的最末端),然后創(chuàng)建對象,一個一個讀取.
typedef CTypedPtrList<CObList, CMyObject*> CMyList;
CMyList ml;
CMyObject* pMyObject = new CMyObject();
ml.AddTail(pMyObject);
CFileException e;
CFile myFile;
myFile.Open("MyFile.txt", CFile::modeCreate|CFile::modeWrite, &e);
CArchive ar(&myFile, CArchive::store);
ml.Serialize(ar);
ar.Close();
myFile.Close();
while (!ml.IsEmpty())
{
delete ml.GetHead();
ml.RemoveHead();
}
//=====================
//where CMyObject is defined by the following files:
//CMyObject.h
class CMyObject : public CObject
{
public:
int i;
void Serialize(CArchive& ar);
CMyObject() { i = 9876;}
protected:
DECLARE_SERIAL(CMyObject)
};
//===================
//CMyObject.cpp
#include "stdafx.h"
#include "CMyObject.h"
IMPLEMENT_SERIAL(CMyObject, CObject, 0)
void CMyObject::Serialize(CArchive& ar)
{
CObject::Serialize( ar );
if( ar.IsStoring() )
ar << i;
else
ar >> i;
}
2.析構函數(shù)可以自己調用
比較吃驚!
但msdn上是這樣說的
Calling a destructor explicitly is seldom necessary. However, it can be useful to perform cleanup of objects placed at absolute addresses. These objects are commonly allocated using a user-defined new operator that takes a placement argument. The delete operator cannot deallocate this memory because it is not allocated from the free store . A call to the destructor, however, can perform appropriate cleanup. To explicitly call the destructor for an object, s, of class String, use one of the following statements:
s.String::~String(); // Nonvirtual call
ps->String::~String(); // Nonvirtual call
s.~String(); // Virtual call
ps->~String(); // Virtual call
自己測試的代碼
#include <iostream>
using namespace std;
class ExplicitlyCallDesCtor
{
public:
ExplicitlyCallDesCtor()
{
cout << "call Constructor" << endl;
}
~ExplicitlyCallDesCtor()
{
cout << "call Destructor" << endl;
}
private:
int member;
};
int main()
{
{
ExplicitlyCallDesCtor o;
cout << "befor Explicitly call" << endl;
o.~ExplicitlyCallDesCtor();
cout << "after Explicitly call" << endl;
cout << "Exit the scope" << endl;
}
cout << "Systemc all" << endl;
}
結果:
call Constructor
befor Explicitly call
call Destructor
after Explicitly call
Exit the scope
call Destructor
Systemc all
microsoft c++ compiler 13 與 GCC 3.4.2下結果相同
3.注意一個不易發(fā)現(xiàn)的死循環(huán)
std::vector<int> IntS;
ints.pushback(...)
for (UINT i=IntS.size()-1;i>=0;i--)
{
....
}