其他分享
首页 > 其他分享> > c – 对非对象使用成员初始化列表是不是很糟糕?

c – 对非对象使用成员初始化列表是不是很糟糕?

作者:互联网

由于我只是在某些情况下必须使用初始化列表,因此我习惯于将所有内容放在初始化列表中,而构造函数只能用于设置成员的值.

就像我在这里做的:

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,initializer-list
来源: https://codeday.me/bug/20190829/1762205.html