Initializing map and set class member variables to empty in C++?

此生再无相见时 提交于 2019-12-04 11:43:31

问题


I have a C++ class with two member variables

std::map<int, Node*> a;

and

std::set<Node*> b;

A style checker used at my University requires all member variables to be initialized in the constructor of the class. How can these member variables a and b be initialized to empty in the constructor of the class they are in?


回答1:


Like this:

class A
{
  public :

  A() : s(),
        m()
  {
  }


  std::set< int > s;
  std::map< int, double > m;
};



回答2:


Like this SomeClass::SomeClass() : a(), b() {}?




回答3:


As both std::set and std::map have "user"-declared default constructors they will be initialized implicitly however you construct your class. You don't have to do anything special to conform with the "style" guide.




回答4:


This check is performed by the g++ compiler, when the -Weffc++ warning option is applied. See Item 4 ("Make sure that objects are initialized before they're used" in Scott Meyers, Effective C++, Book for more information, why it might be reasonable to initialize all members using the member initialization list. Basically he suggests to do this consistently and prefer this over assignments inside constructor bodies.



来源:https://stackoverflow.com/questions/4344464/initializing-map-and-set-class-member-variables-to-empty-in-c

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