4 Ocak 2021 Pazartesi

Rule Of 3

Giriş 
Rule of 3 şudur
If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.
Eğer sınıf belleği silmek için destructor yazmaya ihtiyaç duyuyorsa, muhtemelen copy constructor ve assignment operator'ünü de yazmaya ihtiyaç duyar der.

Rule of Zero İle İlişkisi
Mümkünse Rule of Zero tercih edilmeli. Açıklaması şöyle
The full name of the rule is the rule of 3/5/0.

It doesn't say "always provide all five". It says that you have to either provide the three, the five, or none of them.

Indeed, more often than not the smartest move is to not provide any of the five. But you can't do that if you're writing your own container, smart pointer, or a RAII wrapper around some resource.
Örnek
Elimizde şöyle bir kod olsun
// RAII Class which allocates memory on the heap.
class ResourceManager {
  Resource* resource;
  ResourceManager() {resource = new Resource;}
  // In this class you need all the destructors/ copy ctor/ move ctor etc...
  // I haven't written them as they are trivial to implement
};
Bu kodu rahatlıkla şöyle yaparız. Bu durumda destructor, copy constructor ve copy assignment yazmaya gerek kalmaz
class ResourceManager {
    std::unique_ptr<Resource> resource;
};




Hiç yorum yok:

Yorum Gönder