Default member values best practice

前端 未结 3 1913
一个人的身影
一个人的身影 2020-12-07 10:53

Is it good practice when writing C++11 code to set default values for class members in the header file of the class?

Or is it better to do this in the constructor of

3条回答
  •  悲哀的现实
    2020-12-07 11:15

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

提交回复
热议问题