删除默认类构造函数有什么意义? [英] What's the point of deleting default class constructor?

查看:60
本文介绍了删除默认类构造函数有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为CPP考试做准备,问题之一是:您可以删除默认的类构造函数吗?如果这样做,请问原因是什么?好的,所以显然您可以做到:

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:

class MyClass 
{ 
  public: 
    MyClass() = delete; 
};

但是我不明白你为什么要这么做?

but I do not understand why would you do it?

推荐答案

请考虑以下类:

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
}

现在,假设您不喜欢未初始化的值以及它们可能产生的未定义行为.您可以删除 Foo 的默认构造函数:

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 仍然是一个聚合,但是只有后两个定义有效-第一个定义现在是编译时错误.

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

这篇关于删除默认类构造函数有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆