C++, preventing class instance from being created on the stack (during compiltaion)

前端 未结 5 734
谎友^
谎友^ 2020-12-29 00:29

I know there are methods to prevent a class from being created on the heap, by preventing the user from using the new and delete operator. I am try

5条回答
  •  春和景丽
    2020-12-29 00:52

    Why would the destructor be called while creating an instance of MyClass?

    It isn't. It must be invoked automatically when the instance goes out of scope, though. If it's private, the compiler must not generate that code, hence the error.

    If you think making the destructor private is obscure, another way to restrict a class to dynamic allocation is to make all the constructors private and only have MyClass::create() functions returning dynamically allocated objects:

    class MyClass {
    public:
      static MyClass* create()             {return new MyClass();}
      static MyClass* create(const Foo& f) {return new MyClass(f);}
    private:
      MyClass();
      MyClass(const Foo&);
    };
    

    Note that returning naked pointers to objects that must be deleted is frowned upon. You should return smart pointers instead:

    class MyClass {
    public:
      static std::shared_ptr create()             {return new MyClass();}
      static std::shared_ptr create(const Foo& f) {return new MyClass(f);}
      // ...
    };
    

提交回复
热议问题