ユーザーに提供する関数では基本的に、newで生成したインスタンスを戻り値にしてはいけない
(ユーザーが必ずdeleteしてくれることを期待してはいけない)
#include <iostream> using namespace std; struct base { virtual base() {} virtual void disp() const { cout << "base" << endl; } }; struct derived : public base { virtual derived() {} virtual void disp() const { cout << "derived" << endl; } }; base* factory() { return new derived; } int main() { base* p = factory(); p->disp(); delete p; // 解放忘れるかも return 0; }
だが、shared_ptrのようなスマートポインタを使用すれば話は別だ
#include <iostream> #include <memory> using namespace std; using namespace std::tr1; // C++0xではこの行は不要(std::shared_ptrになる予定なので) struct base { ... }; struct derived : public base { ... }; shared_ptr<base> factory() { return shared_ptr<base>(new derived); } int main() { shared_ptr<base> p = factory(); p->disp(); return 0; // 使い終わったら必ずdelete }
shared_ptrを使用すれば、生成系のデザインパターンがわりと簡単(安全)に実装できる