Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prohibit the construction of object?

How can I prohibit the construction of an object? I mark = delete; all relevant special functions as follows:

struct A
{
    A() = delete;
    A(A const &) = delete;
    A(A &&) = delete;
    void * operator new(std::size_t) = delete;
    void operator delete(void *) = delete;
};
A x{};
A y = {};
A * z = ::new A{};

LIVE EXAMPLE

But x, y and *z can still exist. What to do? I am interested in both cases; static/stack allocation and heap allocation.

like image 855
Tomilov Anatoliy Avatar asked Oct 15 '15 10:10

Tomilov Anatoliy


2 Answers

One option would be to give the class a pure virtual function, and mark it final:

struct A final
{
  virtual void nonconstructible() = 0;
};

[Live example]

like image 113
Angew is no longer proud of SO Avatar answered Sep 19 '22 13:09

Angew is no longer proud of SO


  1. If you want to have just static members, then write namespace A rather than struct A. Ensuing code will be syntactically similar.

  2. To prevent creation of an instance of a class, make it abstract. (Include one pure virtual function). But doing this introduces a v-table into you class, which you might not want.

like image 33
Bathsheba Avatar answered Sep 20 '22 13:09

Bathsheba