How to enforce users to create objects of class derived from mine with “new” only?

邮差的信 提交于 2019-12-03 20:46:03

Make the constructor private and write a static member function that uses new

class IUnknownLike{
public:
  static IUnknownLike * createIUnknownLike(); { return new IUnknownLike(); }

private:
  IUnknownLike (); // private ctor
};

IUnknownLike* obj = createIUnknownLike();

You can make the Base class's destructor protected and smart pointer class his friend.

Thus the users will be unable to create the instance of the class on stack. They'll have to use operator new and smart_pointer class, that will call release and delete.

If you're really intent on doing this for so many classes, use a macro to create the factory method. Something like:

#define FACTORY(NAME) protected: NAME();\
public: static NAME* create ## NAME(){ return new NAME(); }

If you want to pass parameters to the constructors, you'll have to get fancier.

The alternative is to implement the rest of COM and have each class register a factory function with a central object creation system. While an interesting exercise, this all sounds like a terrible idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!