Initializing in constructors, best practice?

后端 未结 7 847
囚心锁ツ
囚心锁ツ 2020-12-07 02:01

I\'ve been programming in C++ a while and I\'ve used both methods:

class Stuff {
public:
     Stuff( int nr ) : n( nr ) { }
private:
     int n;
}

7条回答
  •  粉色の甜心
    2020-12-07 02:23

    One big advantage to using initializers: If an exception is thrown anywhere within the initializer list, the destructors will be called for those members that had already been initialized -- and only for those members.

    When you use the contructor body to initialize the object, it's up to you to handle exceptions properly and unwind the object as appropriate. This is usually much harder to get right.

提交回复
热议问题