深拷贝与浅拷贝的认识

来源:互联网 发布:服装用料软件 编辑:程序博客网 时间:2024/05/21 15:05
首先定义:

浅拷贝:直接复制对象里的字段(value)。若是指针则复制(value),这里的value是指address.非地址指向的内容

深拷贝:如果该字段不是指针,则复制字段,若存在指针,则申请一块新地址存放指向的内容。

拷贝构造函数没有处理静态数据成员

传值:在进入函数前,先通过拷贝函数(若没有拷贝构造函数,则调用默认构造函数,即浅拷贝)建立一个临时对象。函数结束时会调用析构函数销毁该对象。

传引用:把对象直接传过去

以下情况都会调用拷贝构造函数:
一个对象以值传递的方式传入函数体 
一个对象以值传递的方式从函数返回 
一个对象需要通过另外一个对象进行初始化。


一定要区别构造函数和赋值函数。就像声明和定义,初始化和赋值的区别。非常重要

这里感觉英文的书比较好理解,比如define or declaration,value or variables,initial or assignment.

比如:int a=10;//属于初始化,

int a=10;

int c=9;

c=a;//属于赋值;


声明时,初始化=操作,()操作都是调用拷贝构造函数,只有初始化完成后,=操作才是operator=,示例:
Type a;
Type b(a); // 拷贝构造函数
Type a;
Type b = a; // 拷贝构造函数
Type a;
Type b;
b = a;  // operator=(Type&)




string Literals:

I discuss string literals along with pointers because using astring literal in at program generates a ʺconstant pointer to character.ʺ When a string literal appears in an expression,the value used in the expressionis theaddresswhere its characters were stored, not the characters themselves.

Thus, you can assign a string literal to a variable of type ʺpointer to character,ʺ which makes the variable point to where the characters are stored. 

1 C++关于对象传值与传引用的总结  https://www.liuhe.website/index.php?/Articles/single/18 

2  

Java String 详解 - String Literal    http://www.iteye.com/topic/1122514


3  请别再拿“String s = new String("xyz");创建了多少个String实例”来面试了吧   

http://rednaxelafx.iteye.com/blog/774673


0 0
原创粉丝点击