我应该定义默认的构造函数吗? [英] Should i define the default constructor?

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

问题描述

因此,我们正在进行一些同行评审,但这种微小的分歧上升了,

So we were doing some peer review, and this minor disagreement rose up,

即使不执行任何操作也应定义默认构造函数,还是应该让编译器对其进行定义?

Should the default constructor be defined even if it does nothing, or should we let the compiler define it?

到目前为止,没有任何一方可以提出任何主要的优点或缺点.每种样式的优缺点是什么,哪些被认为是清洁器"?

So far, none of the sides could come up with any major advantages or disadvantages. What are the pros and cons of each style and which one is considered "cleaner"?

推荐答案

这很可能以主要基于意见"的形式结束,但是我可以给您一些客观的考虑因素:

This is likely to be closed as "primarily opinion-based," but I can give you some objective points to consider:

  • 如果您定义默认构造函数,而后来有人添加了一个带有参数的构造函数,而忘记了也添加了无参数构造函数,则默认构造函数将消失并且可能会破坏现有代码.明确定义它可以确保即使以后有人添加了一个重载的构造函数,无参数的构造函数仍然存在.

  • If you don't define the default constructor, and someone later adds a constructor with parameters and forgets to also add the parameterless constructor, the default constructor will go away and that could break existing code. Explicitly defining it ensures that even if someone adds an overloaded constructor later, the parameterless one is still there.

如果构造函数在标头中声明并脱机定义(在.cc/.cpp文件中),则以后可以用依赖代码修改实现,而只需重新链接即可.在事实之后声明构造函数必然会影响标头,从而需要重新编译相关代码.

If the constructor is declared in the header and defined out-of-line (in a .cc/.cpp file), then the implementation can later be modified with dependent code only needing to be re-linked. Declaring a constructor after the fact necessarily affects the header, requiring recompilation of dependent code.

  • 仍然需要调用空的离线构造函数,这会花费少量的运行时成本,而使用隐式提供的默认构造函数,编译器可以看到不需要执行任何操作并避免了调用.

显式定义它需要更多的键入操作,并需要更多的代码行.与此相关的费用很小但不为零(键入它所花费的时间,以及代码阅读者阅读它所花费的时间).

Defining it explicitly requires more typing and results in more lines of code. There is a small but nonzero cost associated with this (time taken to type it in, and time taken for readers of the code to read through it).

明确定义该类将使该类不再具有 = default在C ++ 11 中.

Defining it explicitly disqualifies the class from being an aggregate class, unless you use =default in C++11.

是的,这些要点是矛盾的.我想您会发现,流行的观点不是 来明确定义它,但是就语言而言,没有正确或错误的方法.(除非您需要将类型汇总).

Yes, these points are contradictory. I think you will find that the prevailing opinion is not to define it explicitly, but as far as the language is concerned there is no correct or incorrect way. (Unless you need your type to be an aggregate.)

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

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