Can i create class objects with a class that just offers a copy constructor?

122 views Asked by At

Is it possible to create instances of a class that only offers a copy-ctor? Or is it good design to also delete a copy-ctor, if one deletes all other ctors?

struct EmptyClass
{
    EmptyClass() = delete;

    // using compiler generated copy ctor.    

    // empty class, also nothing virtual.

    void fn()
    {
    }
};


int main()
{
    {
        const EmptyClass obj(*static_cast<const EmptyClass*>(nullptr));
        obj.fn();
    }

    // or

    {
        char buffer[sizeof EmptyClass]{};
        const EmptyClass obj(*reinterpret_cast<const EmptyClass*>(buffer);
        obj.fn();
    }

    return 0;
}
1

There are 1 answers

0
Brian Bi On

It's not possible to create instances of an object de novo if the object's only accessible non-deleted constructors are copy and move constructors, with one exception: the object may support aggregate initialization. In your case, EmptyClass is an aggregate so I can do this:

EmptyClass c{};  // doesn't call the default constructor

In order to prevent this, we must first declare the default constructor and then define it as deleted:

struct EmptyClass {
    EmptyClass();
};
EmptyClass::EmptyClass() = delete;

This makes EmptyClass not an aggregate. In this case, it will be impossible to create objects of this type.