默认成员重视最佳实践

在编写 C + + 11代码时,在类的头文件中设置类成员的默认值是否是一种好的做法?

还是在类的构造函数中执行更好?

编辑:

我的意思是:

食物 h :

#include <string>


using std::string;


class Foo{
private:
string greet = "hello";
public:
Foo();
};

VS

Cpp (当然带有必要的头文件,但是没有类内初始化) :

Foo::Foo(){
greet = "hello";
}

哪个更好,为什么?

127937 次浏览

It depends whether you need to stay compatible with older C++ compilers .When you are not using C++11 you have to initialize most members (all non-static) in the constructor. Further many people advocate to explicitly initialize every member even if this means explicitly calling the default ctor. Usually you should place implementation details in a cpp file not in the header file, thus an example would be

Example:
//foo.h


class Foo{
public:
Foo();
private:
std::vector<int> vect;
};


//foo.cpp


Foo::Foo():vect(){
}

In C++11 you have more choices and in class member initializer will become very handy, especially if you have several cors. Here is a good link for more information: http://www.stroustrup.com/C++11FAQ.html#member-init

After Edit: According to your code you are using C++11. To my knowledge there is only few information on good practice concerning the new possibilities but IMHO In class member initializer are very handy to concentrate initialization in one place, which reduces complexity and typing

If a class member is always initialized with the same initial value, then you should make the initializer inline, so as to avoid duplication. If the initial value depends on the constructor, then put it in the constructor initializer list. (And never use assignment in the way you did.)

Example:

class Foo
{
bool done = false;   // always start like this
int qty;
Bar * p;


public:
Foo()                        : qty(0),              p(nullptr)    { }
Foo(int q, Bar * bp)         : qty(q),              p(bp)         { }
explicit Foo(char const * s) : qty(std::strlen(s)), p(new Bar(s)) { }


// ...
};

In this hypothetical example, the member done is always required to start as false, so it's best to write the initializer inline. The other two members, qty and p, can be initialized differently in each of three different constructors, so they are initialized inside the constructors' initializer lists.

A curiosum: Note that providing an inline initializer prevents your class from having a trivial default constructor.

Initializing in headers has the main advantages of keeping code more local and easy to understand. It saves also some typing.

The main disadvantage, in my opinion, is the need to include more headers to get access to constructors. Simple forward declaration won't suffice, making compilation take longer.