c ++默认构造函数constexpr或正确未定义?

时间:2022-11-04 18:57:21

Is it better to declare a default constructor which:

声明默认构造函数是否更好:

  • Allocates default values to the member data and is declared constexpr, or
  • 将默认值分配给成员数据,并声明为constexpr,或

  • leaves all member data undefined?
  • 留下所有成员数据未定义?

I'm thinking mainly in the context of STL containers, e.g. vectors make heavy use of default constructors, so which way is more efficient?

我主要考虑的是STL容器,例如:向量大量使用默认构造函数,那么哪种方式更有效?

1 个解决方案

#1


0  

Like all things in C++, it depends.

像C ++中的所有东西一样,它取决于。

Are you intending to create large buffers of this and both need the optimization of not clearing the memory and are unwilling to put the effort towards allocating unallocated memory yourself?

您是否打算创建大缓冲区并且都需要优化不清除内存并且不愿意自己分配未分配的内存?

Or do you want your programs to be correct more often?

或者您希望您的程序更频繁地更正?

Put that way, default your member data and constexpr your constructor. There are ways that involve a few hoops where you can declare a buffer of uninitialized memory large enough to hold N copies of your class and initialize the data later. (It is true there is no standard compliant portable way to implement std::vector yourself, but that is a defect in the standard that won't impact you in real life very soon.)

这样,默认您的成员数据和constexpr您的构造函数。有一些方法涉及一些箍,你可以声明一个未初始化的内存缓冲区,其大小足以容纳你的类的N个副本,并在以后初始化数据。 (确实没有标准兼容的可移植方式来自己实现std :: vector,但这是标准中的一个缺陷,不会很快影响你在现实生活中。)

#1


0  

Like all things in C++, it depends.

像C ++中的所有东西一样,它取决于。

Are you intending to create large buffers of this and both need the optimization of not clearing the memory and are unwilling to put the effort towards allocating unallocated memory yourself?

您是否打算创建大缓冲区并且都需要优化不清除内存并且不愿意自己分配未分配的内存?

Or do you want your programs to be correct more often?

或者您希望您的程序更频繁地更正?

Put that way, default your member data and constexpr your constructor. There are ways that involve a few hoops where you can declare a buffer of uninitialized memory large enough to hold N copies of your class and initialize the data later. (It is true there is no standard compliant portable way to implement std::vector yourself, but that is a defect in the standard that won't impact you in real life very soon.)

这样,默认您的成员数据和constexpr您的构造函数。有一些方法涉及一些箍,你可以声明一个未初始化的内存缓冲区,其大小足以容纳你的类的N个副本,并在以后初始化数据。 (确实没有标准兼容的可移植方式来自己实现std :: vector,但这是标准中的一个缺陷,不会很快影响你在现实生活中。)