tr1/memory 中带了一个 shared_ptr 的智能指针,也有配套的 weak_ptr,但是没有 scoped_ptr,不过起码可以不用等到 c++11 的编译器了
#include <tr1/memory> #include <stdio.h> class CTest { public: CTest() { printf("CTest\n"); } ~CTest() { printf("~CTest\n"); } }; std::tr1::shared_ptr<CTest> GetSharedTest() { printf("in get\n"); std::tr1::shared_ptr<CTest> pTest(new CTest()); printf("leaving get\n"); return pTest; } int main() { std::tr1::shared_ptr<CTest> pTest = GetSharedTest(); return 0; }
输出
in get CTest leaving get ~CTest
—————————————-
2014-3-17 11:11:26 update 常说要 RAII,来看看文件操作如何 RAII
#include <stdio.h> #include <string> #include <assert.h> #include <tr1/memory> class CFile { public: FILE* fp; CFile(const char* pPathToFile, const char* pMod) { printf("opening %s with mod %s\n", pPathToFile, pMod); fp = fopen(pPathToFile, pMod); } ~CFile() { if (fp) { printf("closing file\n"); fclose(fp); } } private: CFile(CFile const &); CFile& operator=(CFile const &); }; typedef std::tr1::shared_ptr<CFile> FileSharedPtr; int main() { FileSharedPtr pFile(new CFile("test.txt", "w")); assert(pFile->fp != NULL); std::string strGreeting("hello"); fwrite(strGreeting.c_str(), strGreeting.length(), 1, pFile->fp); return 0; }