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
- The Rule of Three
- The Rule of Three
- Rule of Three
- Rule of three
- C++的Rule of Three
- What is The Rule of Three?
- What is The Rule of Three?
- What is The Rule of Three?
- The Big Three Rule
- Way on c & c++ 小记 [六] – Rule of Three, 复制控制
- The Rule of Big Three and half: Copy-and-swap Idiom
- Rule of Sign Extension
- rule of poker
- The rule of game
- The Rule of Method Design
- 大拇指规则 (RULE OF THUMB)
- 拇指规则 rule of thumb
- The rule of name defination
- linux软件管理
- Q:suse 11.1上安装R 3.2.2
- LeetCode 310. Minimum Height Trees(最小高度树)
- C# 矩形面积 0002
- hive和hbase表数据同步
- Rule of Three
- 正则表达式引擎实现体会
- 扩展欧几里得算法
- hbase集群安装(1)-ssh安装及配置
- Android的Touch系统简介(一)
- hbase集群安装(2)-ubuntu下jdk安装
- hbase集群安装(3)-安转Hadoop
- 安卓开发中一些小问题
- complementary prior