开发者

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

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?


Like this:

class A
{
  public :

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


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜