Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'?

后端 未结 6 1029
孤城傲影
孤城傲影 2020-11-30 03:44

Is it possible to prevent stack allocation of an object and only allow it to be instiated with \'new\' on the heap?

6条回答
  •  感动是毒
    2020-11-30 04:15

    This should be possible in C++20 using a destroying operator delete, see p0722r3.

    #include 
    
    class C
    {
    private:
      ~C() = default;
    public:
      void operator delete(C *c, std::destroying_delete_t)
      {
        c->~C();
        ::operator delete(c);
      }
    };
    

    Note that the private destructor prevents it from being used for anything else than dynamic storage duration. But the destroying operator delete allows it to be destroyed via a delete expression (as the delete expression does not implicitly call the destructor in this case).

提交回复
热议问题