CodeBlanks Logo Icon CodeBlanks

Move assignment

Move assignment operatörünü öğrenirsin.

Move assignment

Move assignment zaten var olan bir nesneye rvalue atandığında çalışır. İmzası T& operator=(T&& other) biçimindedir.

Örnek: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. Burada b = std::move(a); ataması move assignment'ı tetikler. other.item std::move ile taşınır ve *this döndürülür. Move constructor yeni nesne yaratırken, move assignment var olan nesnenin içeriğini değiştirir. İkisi de taşıma semantiğinin parçasıdır.

operator= ve *this

Move assignment operatörü *this döndürür; bu, zincirleme atama (a = b = c) sağlar. Kaynak temizliği de yapılmalıdır.

Örnek: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. item = std::move(other.item) satırı eski içeriği serbest bırakıp yeni içeriği taşır. return *this kendisine başvuru döndürür. Eğer sınıf ham işaretçi tutuyorsa, move assignment öncesinde eski kaynağı delete etmek gerekir. std::string gibi sınıflar bunu kendiliğinden yaptığından ek temizlik gerekmez.

Uygulama Bag sınıfına move assignment ekle

Başlangıç kodundaki Bag sınıfına move assignment ekle: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. main içinde b = std::move(a); ile a'yı b'ye taşı ve b.item'i std::cout ile yazdır.

Başlangıç kodu

main.cpp
#include <iostream>
#include <string>
#include <utility>

class Bag {
public:
    std::string item;
    Bag(std::string i) : item(i) {}
    // Move assignment ekle
};

int main() {
    Bag a("Elma");
    Bag b("Muz");
    // a'yı b'ye taşı ve b.item'i yazdır
    return 0;
}

Örnek çözüm

main.cpp
#include <iostream>
#include <string>
#include <utility>

class Bag {
public:
    std::string item;
    Bag(std::string i) : item(i) {}
    Bag& operator=(Bag&& other) {
        item = std::move(other.item);
        return *this;
    }
};

int main() {
    Bag a("Elma");
    Bag b("Muz");
    b = std::move(a);
    std::cout << b.item;
    return 0;
}

Beklenen çıktı

Elma

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 b = std::move(a); hangi işlemi tetikler?

main.cpp
Bag a("Elma"), b("Muz");
b = std::move(a);
  • Copy constructor
  • Move assignment Doğru cevap
  • Copy assignment
  • Move constructor

Açıklama: Var olan nesneye atama move assignment'ı tetikler.

2 İşlemi tetikleyene eşle

Kavram Anlamı
Box b(std::move(a)) Move constructor
b = std::move(a) Move assignment
Box b(a) Copy constructor
b = a Copy assignment

3 Move assignment imzası

Soru
Bag& operator=(Bag____ other) { item = std::move(other.item); return *this; }
Cevap
Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }

Açıklama: Move assignment rvalue referans alır: Bag&&.

Orta seviye bölümündeki tüm dersler