开发者

does this struct need a non-default constructor

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 开发者_C百科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;


1-) If you define any constructor (with 0 or 1 or n parameter) in your struct or class then C++ default constructor will not be created automatically.

So every thing is now depend only on your call to constructor.

if you create object Node* x = new Node(); This must call constructor with no parameter and your class must have constructor with no parameter[Read First Line Again].

Lets check if there is any constructor with no parameter in your struct or class. I say it again if you create any constructor with any number of parameter in C++ then default constructor will not be created by C++ interpreter automatically.

Line 1 is very important to understand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜