问题
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