简体   繁体   English

C ++ 11:如何使用nullptr初始化某个类的指针数组?

[英]C++11: How to initialize array of pointers of some class with nullptr?

I am new to C++. 我是C ++的新手。 I have class named MyDate . 我有一个名为MyDate类。 In addition I have a class named Calendar which has a member type of array of pointers to MyDate objects. 另外,我有一个名为Calendar的类,该类具有指向MyDate对象的指针数组的成员类型。 How should I declare and initialize members of the array to nullptr in the constructor of Calendar ? 我应该如何在Calendar的构造函数中将数组的成员声明并初始化为nullptr

Personally, I'd probably do it like this: 就个人而言,我可能会这样做:

class Calendar {

/* Methods: */

    Calendar() noexcept
    { for (auto & ptr: m_dates) ptr = nullptr; }

/* Fields: */

    /* Array of 42 unique pointers to MyDate objects: */
    std::array<MyDate *, 42> m_dates;

};

PS: You might want to consider using smart pointers like std::unique_ptr or std::shared_ptr instead of raw pointers. PS:您可能要考虑使用诸如std::unique_ptrstd::shared_ptr类的智能指针,而不是原始指针。 Then you wouldn't need to explicitly initialize these in the Calendar constructor at all: 然后,您根本不需要在Calendar构造函数中显式初始化它们:

class Calendar {

/* Fields: */

    /* Array of 42 pointers to MyDate objects: */
    std::array<std::unique_ptr<MyDate>, 42> m_dates;

};

EDIT: Without C++11 features, I'd do this: 编辑:没有C ++ 11功能,我会这样做:

class Calendar {

/* Methods: */

    Calendar()
    { for (std::size_t i = 0u; i < 42u; ++i) m_dates[i] = NULL; }

/* Fields: */

    /* Array of 42 unique pointers to MyDate objects: */
    MyDate * m_dates[42];

};

Smart pointers default-initialize to nullptr : 智能指针默认初始化为nullptr

class Calendar
{
    std::array<std::unique_ptr<Date>, 42> m_dates;
};

Otherwise, std::array is an aggregate, so an empty braced init list will zero-initialize all scalar fields: 否则, std::array是一个聚合,因此空的初始化列表将对所有标量字段进行零初始化:

class Calendar
{
    std::array<Date *, 42> m_dates {};
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM