Rule of Three

《C++ Primer》中称构造函数、赋值操作符重载、复制构造函数为Rule of Three,自己译为“三剑客”。意思是它们常常是一起出现的。为什么呢?目前遇到过的问题是——有非static动态分配的指针成员的时候需要用到析构函数,同时注意到后两者对于指针的默认复制方式是shallow copy,一般需要deep copy。至于其它情况还没遇到。

然后书里的课后题提示说,自己写一个类,重载上面这三个,分别在它们的函数体里面打印函数名,用各种方式来执行它们,自然就会明白其中的规律,代码写出来共享一下,发现运行之后确实豁然开朗了!!!

#include <stdio.h>
#include <string>
using namespace std;

class Test{
public:
    Test() {
        printf("Test()\n");
    }

    Test(const Test& t) {
        printf("Test(const Test& t)\n");
    }

    Test& operator = (const Test& t) {
        printf("Test& operator = (const Test& t)\n");
        return *this;
    }

    ~Test() {
        printf("~Test()\n");
    }
};

Test func1(Test t) {
    printf("func1\n");
    return t;
}

Test func2(Test& t) {
    printf("func2\n");
    return t;
}

Test& func3(Test t) {
    printf("func3\n");
    Test* tt = new Test(t);
    return *tt;
}

Test& func4(Test& t) {
    printf("func4\n");
    return t;
}

int main() {
    Test a;
    Test b(a);
    Test c = a;
    b = c;

    printf("\n----------------\n");

    Test f1 = func1(a);
    printf("\n----------------\n");

    Test f2 = func2(a);
    printf("\n----------------\n");

    Test& f3 = func3(a);
    delete &f3;
    printf("\n----------------\n");

    Test& f4 = func4(a);

    return 0;
}

一个小发现是,(我用的是g++),定义类的对象时,即使用的是等于号,编译器好像会优化成直接调用复制构造函数,比如上面程序里的:Test c = a;(为什么说是优化呢?因为不然的话,应该是先创建c,然后复制一遍a的数据到c里面)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值