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?
-
3See if you can avoid having this array of pointers in the first placeM.M– M.M2016-03-07 20:09:38 +00:00Commented Mar 7, 2016 at 20:09
Add a comment
|
2 Answers
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 {};
};
1 Comment
jotik
Indeed, you seem to be correct according to Clang and GCC. However, to work around a
-Wmissing-field-initializers warning it were perhaps better to use std::array<Date *, 42> m_dates {{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. 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];
};
6 Comments
M.M
std::array<MyDate *, 42> m_dates {}; is much simplersarit rotshild
@jotik- should I include some special library for the nullptr?
jotik
@saritrotshild No, its a C++11 feature. But you need
#include <array> for std::array and #include <memory> for std::unique_ptr/std::shared_ptr.sarit rotshild
@jotik- I get 2 errors.error:1. #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. 2.error:'array' in namespace 'std' does not name a type.
jotik
Seems that you have an old compiler which does not fully support C++11. Since
nullptr, std::array, and std::unique_ptr/std::shared_ptr are C++11 features, you must use a compiler supporting C++11. If you want to use C++03 or earlier, you should not have used nullptr in the original question, but NULL. In this case the question must be re-tagged etc. I added to my answer an example for earlier versions of C++. |