Is member value in the class initialized when an object is created?

守給你的承諾、 提交于 2019-12-31 05:15:36

问题


I'm writing a hash class:

struct hashmap {
  void insert(const char* key, const char* value);
  char* search(const char* key);
 private:
  unsigned int hash(const char* s);
  hashnode* table_[SIZE]; // <--
};

As insert() need to check if table[i] is empty when inserting a new pair, so I need all pointers in the table set to NULL at start up.

My question is, will this pointer array table_ be automatically initialized to zero, or I should manually use a loop to set the array to zero in the constructor?


回答1:


The table_ array will be uninitialized in your current design, just like if you say int n;. However, you can value-initialize the array (and thus zero-initialize each member) in the constructor:

struct hash_map
{
    hash_map()
    : table_()
    {
    }

    // ...
};



回答2:


You have to set all pointers to NULL. You do not have to use a loop, you can call in the contructor :

memset(table_, 0, SIZE*sizeof(hashnode*));


来源:https://stackoverflow.com/questions/18120162/is-member-value-in-the-class-initialized-when-an-object-is-created

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