What is benefit of this constructor definition [du

2019-02-22 13:04发布

I was just going through random pages on Cprogramming.com and noticed the Constructors and Destructors tutorial/example page. They have used the following method of defining a constructor:

class String
{
    private:
        char *str;
        int size;
    public:
        String() : str(NULL), size(0) { }  // <- This statement
        String(int size) : str(NULL), size(size) {  // <- And this one
            str = new char[size];
        }
}

I've been using the good old fashioned definition of constructors with the magic this pointer:

String() { 
    this->str = NULL;
    this->size = 0;
}
String(int size) {
    this->size = size;
    this->str = new char[size];
}

Is there any added benefit in the first declaration beside the obvious smaller code (less number of lines)?

PS: It has been quite a few years since I last did write something in C++.

3条回答
2楼-- · 2019-02-22 13:38

i was like you, with the back old collage knowledge this usage seems weird. But then understand that by using this technique, custom class implementations give better performance on runtime. And here is a long explanation about initiatization lists from the father of C++.

查看更多
Root(大扎)
3楼-- · 2019-02-22 13:46

Those are constructor initialization lists, and for fundamental types there is no difference with respect to the form you are used to, which is based on assignment rather than initialization.

However, for user-defined types there might be a difference in terms of performance (and semantics perhaps) between:

  1. default-constructing an object and then assigning a value to it, and
  2. directly initializing it with that value.

Also, you do not have a choice for those types that are not default-constructible other than using a member initialization list to initialize them, and you do not have a choice for const and reference members either, that must be initialized immediately.

查看更多
Animai°情兽
4楼-- · 2019-02-22 13:54

Constructing objects in C++ is done in three steps:

  1. Memory is aquired
  2. Member variables are initialized
  3. The constructor is executed.

The constructor definition String() : str(NULL), size(0) {} assigns the proper value to the variables in step 2.

The constructor definition String() { this->str = NULL; this->size = 0; } does this in step 3. Step 2 is, however, executed nevertheless. So this kind of assigning the proper value to the member variables is less efficient.

查看更多
登录 后发表回答