这个构造函数定义的好处是什么 [英] What is benefit of this constructor definition

查看:149
本文介绍了这个构造函数定义的好处是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚通过Cprogramming.com上的随机页面,注意到构造函数和析构函数教程/示例页面。他们使用以下方法定义构造函数:

  class String 
{
private:
char * str;
int size;
public:
String():str(NULL),size(0){} // < - 此语句
String(int size):str ){//< - 这个
str = new char [size];
}
}



我一直在使用良好的老式定义构造函数带有这个指针:

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

在第一个声明中有明显更小的代码

PS:自从我上次在C ++中写了一些东西以来,已经有几年了。

解决方案

这些是构造函数初始化列表,并且对于基本类型,您使用的形式没有区别,这是基于赋值而不是初始化。



但是,对于用户定义的类型,在性能(和语义可能)之间可能存在差异:



<
  • 默认构建对象,然后为其分配值,

  • 直接用该值初始化它。

  • 此外,除了使用成员初始化列表初始化它们之外,你不能选择不是默认可构造的类型,没有 const 和引用成员的选择,必须立即初始化。


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

    解决方案

    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.

    这篇关于这个构造函数定义的好处是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆