Rule of Three

来源:互联网 发布:cv source数据库 复旦 编辑:程序博客网 时间:2024/06/06 02:38

《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