C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意

来源:互联网 发布:多益网络面试题 编辑:程序博客网 时间:2024/04/27 23:29
  1. 一个空类时,编译器会默认生成构造函数,拷贝构造函数,赋值函数,析构函数
  2. 一个类如果重写拷贝构造函数,那么必须自定义一个构造函数。如下代码会编译出错:error C2512: “B”: 没有合适的默认构造函数可用
    class B{public:    B(const B &b)    {    }};int main(void){    B b;    getchar();    return 0;}
    修正为:
    class B{public:    B() {}    B(const B &b)    {    }};int main(void){    B b;    getchar();    return 0;}

  3. 拷贝构造函数和赋值函数的正确写法(if(this != &b))
    class B{public:    B(int v)    {        m_value = v;    }    B(const B &b)    {        m_value = b.m_value;    }    B &operator =(const B &b)    {        if(this != &b)        {            m_value = b.m_value;        }        return *this;    }private:    int m_value;};

  4. 函数返回值是对象时,要考虑return语句的效率。
    B createObj0(void){    return B(0);}B createObj1(void){    B b(0);    return b;}
    createObj0创建一个临时对象并返回它,编译器直接把临时对象创建并初始化在外部存储单元中,省去了拷贝和析构的过程。createObj1则是先创建b对象,然后拷贝构造把b拷贝到外部存储单元中去,接着还会析构掉b对象。请对比下列两组代码及运行结果:
    #include <stdio.h>int g_counter = 0;class B{public:    B(void)    {        m_value = g_counter++;        printf("B() m_value=%d\n", m_value);    }    ~B()    {        printf("~B() m_value=%d\n", m_value);    }    B(const B &a)    {        m_value = g_counter++;        printf("B(const B &a) m_value=%d\n", m_value);    }    B &operator=(const B&a)    {        printf("B &operator=(const B&a)\n");        return *this;    }private:    int m_value;};B createObj0(const B b){    B bb(b);    return bb;}B createObj1(const B b){    return B(b);}int main(void){    B __b;    B _b = createObj0(__b);return 0;}
    运行结果:
    #include <stdio.h>int g_counter = 0;class B{public:    B(void)    {        m_value = g_counter++;        printf("B() m_value=%d\n", m_value);    }    ~B()    {        printf("~B() m_value=%d\n", m_value);    }    B(const B &a)    {        m_value = g_counter++;        printf("B(const B &a) m_value=%d\n", m_value);    }    B &operator=(const B&a)    {        printf("B &operator=(const B&a)\n");        return *this;    }private:    int m_value;};B createObj0(const B b){    B bb(b);    return bb;}B createObj1(const B b){    return B(b);}int main(void){    B __b;    B _b = createObj1(__b);return 0;}

    运行结果:
0 0
原创粉丝点击