newbie here, in order to help sort out problems in my C++ project, I am compiling with the -Weffc++ option in g++.
It's giving me hundreds of warnings about "warning ... should be initialized in the member initialization list"
Is this really necessary seeing as it will a) take a bit of time to 开发者_C百科write them all in, and b) make make things messier when I was happy initialising variables when they are need only.
But more specifically, how do I initialise a std::vector?
Is this the way, ie just putting a 0 in brackets? My header:
class Blade;
class Postpro {
public:
Postpro(string fName) : theFileName(fName),
blade(NULL),
sizes(10),
t(std::vector<double>(0){};
~Postpro(){};
void test();
private:
string theFileName;
Blade* blade;
int sizes;
std::vector<double> t;
}
And then in the cpp I just resize the vector if I want to use it?
void Postpro::test() {
blade = new Blade;
t.resize(37);
}
Thanks
It does not take that much time to type, because you have typed too much:
Instead of
t(std::vector<double>(0))
you could write
t(0)
which should be the same as
t()
The warning might be a bit too pedantic. Classes with a default constructor will be automatically initialized anyway. A warning flag to alert you only of uninitialized POD members would seem more valuable (otherwise you get too much noise).
May-be the use is that it shows the reader that you indeed meant to use the default constructor to initialize that member.
Zero might be a valid value for a vector, but I have never seen that.
You really don't have to give any value at all, since vector has a default constructor. Just a t()
would do.
And the warning is just a warning, the vector's default constructor will be called anyway.
You can do this the way you did it, but there is no point -- the default constructor does exactly the same job. It is better to use initializer lists, but if it leads to unreadable or unnecessarily complicated code, it's perfectly fine to initialize (to be more precise, reset them from their default values) the member variables in the constructor body.
精彩评论