(原創) 哪些地方會用到Copy Constructor和Assignment Operator? (C/C++)

C#、Java都沒有copy constructor,所以這對大部分programmer都很陌生,簡單地說,凡需要copy的地方,就需要copy constructor:

1.由copy-initialization方式建立物件。
Ex.
Foo foo1;
Foo foo2(foo1);
以上直接使用copy constructor。

string s = "C++ Primer";
Foo foo = Foo();
此時是先由default constructor建立一個temporary object後,再由copy constructor將temporary object 『copy』給物件。

2.以by value的方式傳進function和由function return值。
Ex.
int Foo(int n);
只要不是使用by reference的方式,就得使用copy constructor。

3.建立STL container中的element。
Ex.vector<string> svec(5);
先由string的default constructor建立一個temporary string object,再由string的copy constructor『copy』到vector中每個element。

4.由initialization list建立array。
Ex.int ia[] = {1, 2, 3};
先由int default contructor先建立temporary int object,再由int的copy contructor『copy』到array中。

所以copy constructor其實是無所不在的,只是我們從來沒有發現,雖然C++ compiler會自己synthesize copy constructor,但也允許我們自己定義自己的Copy Constructor,這與C#、Java不同。

而assignment operator呢?
Foo foo1;
Foo foo2;
foo2 = foo1;
以上會執行foo2的assignment operator。

所以簡單的說,copy constructor和assignment operator都在做『copy』的動作,當資料是pointer,也就是動態資料時,就必須重新改寫,否則只會copy pointer,而不是copy data。

posted on 2007-01-14 22:32  真 OO无双  阅读(11744)  评论(0编辑  收藏  举报

导航