问题
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