简体   繁体   中英

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;
};

像这样SomeClass::SomeClass() : a(), b() {}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM