I have the following struct in C++, and I wondered if I need to define a non-default constructor for it when I use it as follows: boost::shared_ptr<node> p_node = boost:shared_ptr<node>();
struct node
{
std::string name;
std::map<std::string, std::vector<variant> > values; // it is possible that nodes contain as a value, key/value pairs so we need a map
NodeType type; //Enum
typedef struct attrib
{
std::string key;
variant value; //Boost::variant
};
std::vector<attrib> attributes;
boost::shared_ptr<node> childnode;
};
"does this POD need a non-default constructor"... what POD? POD's don't contain complex objects like strings and maps. POD stands for plain old data, which is things like doubles and char arrays.
Whether you need a constructor depends on whether you want to make sure all the data is initialised in some sane state. std::map, std::vector and std::string are all initialised for you to be empty. The other boost::shared_ptr will be NULL. attrib is only a type and you won't initially have any attrib objects, so no worries there. But, your NodeType enum isn't initialised anywhere unless you do it yourself in a constructor. Does that matter? Only you can decide, but technically you MUST make sure you assign to it somewhere before reading from it, otherwise you technically get undefined behaviour.
Note that this is not a POD.
Yes, this struct needs a default ctor, because otherwise the enum member will have an undefined value after default construction. It doesn't matter how you use it -- or, as in your example code boost::shared_ptr<node> p_node = boost:shared_ptr<node>(); do not use it at all, as that just initializes a NULL shared ptr and you could just as well have written boost::shared_ptr<node> p_node;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With