Is it possible to prevent stack allocation of an object and only allow it to be instiated with \'new\' on the heap?
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).