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

不问归期 提交于 2020-01-06 20:04:00

问题


I am new to C++. I have class named MyDate. In addition I have a class named Calendar which has a member type of array of pointers to MyDate objects. How should I declare and initialize members of the array to nullptr in the constructor of Calendar?


回答1:


Smart pointers default-initialize to 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:

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



回答2:


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. Then you wouldn't need to explicitly initialize these in the Calendar constructor at all:

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:

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];

};


来源:https://stackoverflow.com/questions/35849693/c11-how-to-initialize-array-of-pointers-of-some-class-with-nullptr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!