What's the point of deleting default class constructor?

后端 未结 4 2187
轻奢々
轻奢々 2021-02-01 01:26

I\'m preparing for my CPP exam and one of the question is: Can you delete default class constructor and if so, what would be the reason to do so? OK, so obviously you can do it:

4条回答
  •  庸人自扰
    2021-02-01 01:34

    Consider the following class:

    struct Foo {
        int i;
    };
    

    This class is an aggregate, and you can create an instance with all three of these definitions:

    int main() {
        Foo f1;     // i uninitialized
        Foo f2{};   // i initialized to zero
        Foo f3{42}; // i initialized to 42
    }
    

    Now, let's say that you don't like uninitialized values and the undefined behaviour they could produce. You can delete the default constructor of Foo:

    struct Foo {
        Foo() = delete;
        int i;
    };
    

    Foo is still an aggregate, but only the latter two definitions are valid -- the first one is now a compile-time error.

提交回复
热议问题