gpt4 book ai didi

c++ - 对非对象使用成员初始化列表不好吗?

转载 作者:太空狗 更新时间:2023-10-29 20:37:51 24 4
gpt4 key购买 nike

因为在某些情况下我只需要使用初始化列表,所以当构造函数只用于设置成员的值时,我养成了将所有内容都放在初始化列表中的习惯。

就像我在这里所做的那样:

template <typename generic>
class setsPool
{
protected:

set<generic> *pool;
size_t maxSets;
generic maximumValue, minimumValue;

public:

setsPool() = delete;

explicit setsPool( size_t maxSets ) :
pool(new set<generic>[maxSets]), maxSets(maxSets),
maximumValue(0), minimumValue(0) {}

setsPool( size_t maxSets, generic minimumValue, generic maximumValue ) :
pool(new set<generic>[maxSets]), maxSets(maxSets),
minimumValue(minimumValue), maximumValue(maximumValue) {}

// ...
};

而不是这样做:

template <typename generic>
class setsPool
{
// ... same stuff

public:

setsPool() = delete;

explicit setsPool( size_t maxSets )
{
this->pool = new set<generic>[maxSets]);
this->maxSets = maxSets;
this->maximumValue = minimumValue = 0;
}

setsPool( size_t maxSets, generic minimumValue, generic maximumValue )
{
this->pool = new set<generic>[maxSets]);
this->maxSets = maxSets;
this->maximumValue = maximumValue;
this->minimumValue = minimumValue;
}

// ...
};

以这个真实的代码为例,我想知道这样做是否有任何缺点(当我不是真的必须时使用初始化列表)我在这里找到的关于初始化列表的问题似乎并没有说清楚它是否在不必要的情况下使用它是错误的

  • 我的代码是否会因此变得效率较低速度较慢
  • 它是否配置了某种不良做法
  • 我有什么理由要为写这样一段代码而鞭打自己吗?

最佳答案

据我所知,使用成员(初始化程序)列表(没有“成员”,初始化程序列表指的是 different concept introduced in C++11 )通常被认为更好。没有它,我相信它最终会默认构造成员,然后再在构造函数主体中替换它们(可能取决于编译器/优化级别)。

作为支持,我将您指向MSDN :

Member Lists

Initialize class members from constructor arguments by using a member initializer list. This method uses direct initialization, which is more efficient than using assignment operators inside the constructor body.

然后 cppreference (强调已添加):

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

这意味着构造函数主体中的任何赋值都在重新分配已经(默认)构造的成员。

正如 Neil 提到的,对于 POD 类型,如果未在成员初始化列表中指定,则它们不是默认构造的(例如设置为 0)。因此,如果您仅在构造函数主体中设置它们,则不会进行冗余初始化,但使用成员初始化列表也不会花费您任何费用。

关于c++ - 对非对象使用成员初始化列表不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com