Initializing in constructors, best practice?

2020-02-01 19:47发布

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

Or

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

Note: This is not the same as this, similar but not the same.

What is considered best practice?

标签: c++
7条回答
我想做一个坏孩纸
2楼-- · 2020-02-01 20:16

Use the initializer list when possible. For an int, it doesn't matter much either way, but for a more complex member object, you'd end up with the default constructor of the object being called, followed by an assignment to that object, which is likely to end up being slower.

Plus, you have to do it that way anyway for const members or members which don't have a default constructor.

查看更多
登录 后发表回答