Move constructor
- C++ kursu
- Orta seviye
- Ders 102/116
- 5 dk
Move constructor ile verimli taşıma öğrenirsin.
Move constructor
Bir move constructor kaynağı kopyalamak yerine çalar. İmzası T(T&& other) biçimindedir. Bu, pahalı kopyaları önler.
Örnek: Box(Box&& other) : content(std::move(other.content)) {}. Burada other'ın content üyesi std::move ile taşınır ve yeni nesnenin content'ine aktarılır. Normal kopyalama olsaydı dize kopyalanırdı; taşıma ise yalnızca işaretçiyi devreder. Box b(std::move(a)); çağrısı move constructor'ı tetikler. Kaynak sınıf sonrasında boş kalır.
Move constructor ne zaman çağrılır?
Move constructor, yeni bir nesne rvalue'dan başlatıldığında çağrılır. Bu ya std::move ile ya da geçici bir değer döndüren fonksiyon sonucuyla olur.
Örnek: Box b(std::move(a)); ve Box b = makeBox(); (eğer makeBox bir Box döndürüyorsa) her ikisi de move constructor'ı çağırır. İlk durumda std::move açıkça a'yı rvalue'ya çevirir. İkinci durumda dönen geçici değer zaten rvalue'dur. Derleyici bu ayrımı otomatik yapar; move constructor tanımlıysa kopyalama yerine taşıma kullanılır.
Uygulama Box sınıfına move constructor ekle
Başlangıç kodundaki Box sınıfına bir move constructor ekle: Box(Box&& other) : content(std::move(other.content)) {}. main içinde std::move ile a'yı b'ye taşı ve b.content'i std::cout ile yazdır.
Başlangıç kodu
#include <iostream>
#include <string>
#include <utility>
class Box {
public:
std::string content;
Box(std::string c) : content(c) {}
// Move constructor ekle
};
int main() {
Box a("Merhaba");
// a'yı b'ye taşı ve b.content'i yazdır
return 0;
}Örnek çözüm
#include <iostream>
#include <string>
#include <utility>
class Box {
public:
std::string content;
Box(std::string c) : content(c) {}
Box(Box&& other) : content(std::move(other.content)) {}
};
int main() {
Box a("Merhaba");
Box b(std::move(a));
std::cout << b.content;
return 0;
}Beklenen çıktı
Merhaba
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Move constructor imzası
Box(Box____ other) : content(std::move(other.content)) {}
Box(Box&& other) : content(std::move(other.content)) {}
Açıklama: Move constructor rvalue referans alır: Box(Box&& other).
2 Parçayı rolüne eşle
| Kavram | Anlamı |
|---|---|
Box(Box&& other) |
Move constructor |
std::move(other.content) |
İçerik taşıma |
T(T&&) |
Move imzası |
Box b(std::move(a)) |
Taşıma çağrısı |
3 Move constructor hangi parametre türünü alır?
Box(Box&& other);- rvalue referans (T&&) Doğru cevap
- lvalue referans (T&)
- Değer (T)
- İşaretçi (T*)
Açıklama: Move constructor rvalue referans (T&&) alır.