Copy Constructor vs Move Constructor: Ne Zaman Hangisi Çalışır?

# Copy Constructor vs Move Constructor: Ne Zaman Hangisi Çalışır?

C++'da bir nesneyi başka bir nesneye atarken iki yöntem vardır. Copy constructor nesnenin tam bir kopyasını yapar, move constructor ise kaynakları taşır. Hangisinin çalışacağını anlamak performans için önemlidir.

Copy constructor, mevcut bir nesneyi kopyalayıp yeni bir nesne oluşturur. Orijinal nesne değişmez.

1#include <iostream>
2using namespace std;
3
4class Veri {
5public:
6int* dizi;
7int boyut;
8
9Veri(int n) {
10boyut = n;
11dizi = new int[n];
12cout << "Constructor cagrildi\n";
13}
14
15// Copy constructor
16Veri(const Veri& other) {
17boyut = other.boyut;
18dizi = new int[boyut];
19for(int i = 0; i < boyut; i++)
20dizi[i] = other.dizi[i];
21cout << "Copy constructor cagrildi\n";
22}
23
24~Veri() {
25delete[] dizi;
26}
27};
28
29int main() {
30Veri v1(5);
31Veri v2 = v1; // Copy constructor calisir
32return 0;
33}

Çıktı:

1Constructor cagrildi
2Copy constructor cagrildi

Gördüğün gibi `v2 = v1` yaptığında copy constructor çalışıyor. Yeni bellek ayrılıyor, veriler kopyalanıyor.

Move constructor, kaynakları taşır. Orijinal nesne boşaltılır, yeni nesne kaynakları alır. Daha hızlıdır.

Reklam · TEST
AdSense Test ReklamıYazı arası (gönderi içi) · Yazı arası
1#include <iostream>
2using namespace std;
3
4class Veri {
5public:
6int* dizi;
7int boyut;
8
9Veri(int n) {
10boyut = n;
11dizi = new int[n];
12cout << "Constructor cagrildi\n";
13}
14
15// Move constructor
16Veri(Veri&& other) {
17boyut = other.boyut;
18dizi = other.dizi; // Kaynagi tasi
19other.dizi = nullptr; // Orijinali bosalt
20cout << "Move constructor cagrildi\n";
21}
22
23~Veri() {
24delete[] dizi;
25}
26};
27
28int main() {
29Veri v1(5);
30Veri v2 = move(v1); // Move constructor calisir
31return 0;
32}

Çıktı:

1Constructor cagrildi
2Move constructor cagrildi

Copy constructor çalışır:
- Var olan bir nesneyi kopyaladığında: `Veri v2 = v1;`
- Fonksiyona const referans geçtiğinde

Move constructor çalışır:
- Geçici nesneyi taşıdığında: `Veri v2 = Veri(5);`
- `move()` kullandığında: `Veri v2 = move(v1);`
- Fonksiyondan nesne döndürüldüğünde (RVO)

1#include <iostream>
2using namespace std;
3
4class Veri {
5public:
6int* dizi;
7
8Veri(int n) { dizi = new int[n]; }
9Veri(const Veri& other) { cout << "Copy\n"; }
10Veri(Veri&& other) { cout << "Move\n"; }
11~Veri() { delete[] dizi; }
12};
13
14int main() {
15Veri v1(5);
16Veri v2 = v1; // Copy calisir
17Veri v3 = Veri(10); // Move calisir (gecici nesne)
18Veri v4 = move(v1); // Move calisir (acik move)
19return 0;
20}

Çıktı:

1Copy
2Move
3Move

Copy constructor kalıcı nesneleri kopyalar, move constructor geçici nesneleri taşır. Modern C++'da move constructor kullanmak bellek ve hız açısından daha verimlidir.

Reklam · TEST
AdSense Test ReklamıGönderi altı · Görüntülü
konu hakkında tepkinizi verebilirsiniz