前言
在c++中参数传递有两种形式:值传递和引用传递。这两种方式的区别我不在此说,自行补上,如果你不知道的话。我先上python代码,看完我们总结一下,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
# copy module import
import copy
# number and string
a = 12
a1 = a
a2 = copy.copy(a)
a3 = copy.deepcopy(a)
# look addr
print ( "==========number=======" )
print ( id (a))
print ( id (a1))
print ( id (a2))
print ( id (a3))
s = '12345'
s1 = s
s2 = copy.copy(s)
s3 = copy.deepcopy(s)
# look addr
print ( "==========String=======" )
print ( id (s))
print ( id (s1))
print ( id (s2))
print ( id (s3))
# others
target = {
'name' : 'ckmike' ,
'age' : 25 ,
'boxes' :[
'LV' ,
'Prada' ,
'KUQI'
]
}
target1 = target
target2 = copy.copy(target)
target3 = copy.deepcopy(target)
print ( "==========dict-1=======" )
print ( id (target))
print ( id (target1))
print ( id (target2))
print ( id (target3))
print ( "==========dict-2=======" )
print ( id (target[ 'boxes' ]))
print ( id (target1[ 'boxes' ]))
print ( id (target2[ 'boxes' ]))
print ( id (target3[ 'boxes' ]))
|
输出结果:
==========number=======
10943360
10943360
10943360
10943360
==========String=======
140567123944648
140567123944648
140567123944648
140567123944648
==========dict-1=======
140567124625088
140567124625088
140567124625160
140567123938760
==========dict-2=======
140567099339272
140567099339272
140567099339272
140567099339464
总结:
对于数值、字符串而言,不管是赋值符号还是浅拷贝、深拷贝,都是引用的内存中的同一份值,变量指向同一地址。
对于非数值非字符串而言,浅拷贝只会拷贝对象的第一层,深拷贝则会把所有层都进行拷贝。
原文链接:http://blog.51cto.com/4837471/2176384