2

I have a class, that doesn't have any members at all. And so, it is not intended to be instantiated. So, I deleted default c-r. That forbids any construction except list-initialization. Is there any way to forbid it too?

class Empty{
//No non-static data members
Empty()=delete;
};

Empty A{};// is allowed
Empty A ={};//is allowed too
//Empty A; ok, forbidden
//Empty A=Empty(); ok, forbidden

1 Answers1

4

Empty A{}; works because Empty is an aggregate. Merely deleting the default constructor is insufficient to prevent it from being an aggregate (in C++17; in C++20, this will work).

The simplest way to do this is to give it a private member, of type char so that the type's size won't change. Alternatively, you can give it a private default constructor that isn't = defaulted.

However, just because a type is not meant to be used to make an object does not mean you should take special care to prevent it from doing so. std::enable_if<blah> is a type too, and objects of that type are not meant to be constructed. But you can still do it.

You shouldn't take these steps unless there is a genuine problem that would be caused by the user creating an object of that type.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Another ugly hack would be adding a user-provided constructor, e.g. `Empty(dummy) {}; private: struct dummy{};` – M.M Nov 05 '16 at 06:20