C++三大函数(The Big Three)
来源:互联网 发布:nba总决赛欧文数据统计 编辑:程序博客网 时间:2024/06/14 16:08
C++三大函数(The Big Three)
转自:http://www.cnblogs.com/chenyg32/p/3649190.html
C++三大函数:
- 析构函数
- 复制构造函数
- operator=
析构函数
函数模样:~S()
当一个对象超出作用域或执行delete的时候,析构函数就被调用。
复制构造函数
函数模样:S(const S& s)
以下情况,复制构造函数均会被调用:
声明的同时初始化:
S s1 = s2; //注意此时虽然出现=,但是不是调用operator=哦S s1(s2);
调用函数时使用按值传递(而不是按引用传递)
void f(S s);S s1;f(s1);
通过值返回对象
S f(){ S s1; return s1;}
operator=
函数模样:const S& operator=(const S& s)
当=应用于两个已经构造的对象时,就调用复制赋值运算符operator=。
S s1;s1 = s2; //注意与S s1 = s2; 的区别
注意事项:
三大函数不手动实现的时候,会使用默认的版本。比如operator=的默认版本会依次为数据成员复制,如果是基本数据类型自然没什么问题,但当数据成员含有指针的时候,operator的只会进行
浅复制
,即只是指针本身被复制,而不是指针所指向的内容被复制。见下例。class S{ public: int *p; S(int x=0){p=new int(x);}};void f(){ S s1(2), s2; S s3 = s1; s2 = s1; *s1.p=3; cout << *s1.p << ' '<< *s2.p << ' ' << *s3.p << endl;//3 3 3}
很明显这不是我们想要的,我们想让不同的对象的值不互相影响,此时需要实现
深复制
,见下例。class S{ public: int *p; S(int x=0){p=new int(x);} S(const S& rhs) { p = new int(*rhs.p); } const S& operator=(const S& rhs) //rhs=right-hand side { if (this != &rhs) //检查是否复制自身 *p = *rhs.p; return *this; }};void f(){ S s1(2), s2; S s3 = s1; s2 = s1; *s1.p=3; cout << *s1.p << ' '<< *s2.p << ' ' << *s3.p << endl; //3 2 2}
0 0
- C++三大函数(The Big Three)
- C++三大函数(The Big Three)
- big three三大函数:拷贝构造拷贝赋值析构函数
- The Big Three Rule
- C++- Big Three in C99
- 类的the big three原则
- Big-Three
- C++的The Big Three and A Half 是什么
- C(1908)The Big Escape
- C++面向对象编程<六>:Big Three,三个特殊函数
- three.js中的三大组件
- String的Big-Three
- c++ big three
- C++中的Big Three
- C++ 之 Big Three
- Big Three+noncopyable
- C++ Big Three
- codeforces #328 C. The Big Race
- Rabbitmq集群高可用
- Tomacat 环境变量的设置
- python2.7:文件编码检测chardet 详解
- 扒一扒HTTPS网站的内幕
- iOS开发基础-UIButton的使用
- C++三大函数(The Big Three)
- 省市二级显示jquery
- java代码解析excel文件(包含日期、小数的处理)
- ibatis 批量插入,批量更新,批量删除,xml与Java代码实现方式
- 2015最流行的Android组件、工具、框架大全
- select选中方法
- Windows Direct3D Intro - Device Lost
- Android使用fitsSystemWindows属性实现--状态栏【status_bar】各版本适配方案
- opensips介绍