🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Smart pointers: unique_ptr, shared_ptr, weak_ptr and RAII

Move ownership safely between functions, tie a C-style driver resource to a unique_ptr with a custom deleter, and break shared_ptr cycles with weak_ptr.

You met smart pointers in the memory management lesson: an object created with make_unique was deleted when it went out of scope, and shared_ptr kept a counter. In real projects the question is a little harder: in a measurement system, who creates the sensor objects, who stores them, and who only reads them? How do you safely close a resource that comes from a C library, such as a serial port or a file handle? If a panel must know its circuits and each circuit must know its panel, why do the counters never reach zero? In this lesson we will learn to use smart pointers as a language of ownership. Someone reading the code should be able to look at a parameter's type and see the answer to "does this function take and keep the object, or does it only look at it?"

Moving ownership: factories, std::move and functions that only use

Three simple rules are enough:

  • A function that creates and hands over an object returns std::unique_ptr<T> (a factory).
  • The place that takes and keeps the object takes over the unique_ptr with std::move.
  • A function that only uses the object takes a reference (const T&) or a raw pointer; it does not take ownership.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class Sensor {
public:
    Sensor(std::string ad, double kazanc) : ad_(std::move(ad)), kazanc_(kazanc) {
        std::cout << "[+] " << ad_ << '\n';
    }
    ~Sensor() { std::cout << "[-] " << ad_ << '\n'; }
    double oku(int ham) const { return ham * kazanc_; }
    const std::string& ad() const { return ad_; }

private:
    std::string ad_;
    double kazanc_;
};

// Fabrika: sahipligi cagirana verir
std::unique_ptr<Sensor> sensorOlustur(const std::string& ad, double kazanc) {
    return std::make_unique<Sensor>(ad, kazanc);
}

// Sadece kullanir: sahiplik almaz
void raporla(const Sensor& s, int ham) {
    std::cout << s.ad() << ": " << s.oku(ham) << '\n';
}

int main() {
    std::vector<std::unique_ptr<Sensor>> hat;
    hat.push_back(sensorOlustur("akim", 0.01));

    auto gerilim = sensorOlustur("gerilim", 0.5);
    raporla(*gerilim, 460);
    hat.push_back(std::move(gerilim));          // sahiplik vektore gecti
    std::cout << "gerilim bos mu? " << (gerilim == nullptr ? "evet" : "hayir") << '\n';

    for (const auto& s : hat) raporla(*s, 250);
    hat.erase(hat.begin());                     // akim sensoru hemen silinir
    std::cout << "main bitiyor\n";
    return 0;
}
[+] akim
[+] gerilim
gerilim: 230
gerilim bos mu? evet
akim: 2.5
gerilim: 125
[-] akim
main bitiyor
[-] gerilim

The key points:

  • The return type of sensorOlustur says "you are the owner of this object now". Nothing is copied on return; the unique_ptr is moved.
  • std::move(gerilim) does not move the object; it hands over ownership. The sensor stays at the same place in memory; the only thing that changes is who deletes it. After the move, gerilim is empty and can be compared with nullptr, but trying to reach the object through it is a bug.
  • raporla takes a const Sensor&. This function does not care about the sensor's lifetime, so it has no reason to take a smart pointer. When calling it we pass the object itself with *gerilim.
  • When hat.erase(hat.begin()) removed the unique_ptr from the vector, the current sensor was deleted right then. That is why "[-] akim" appears before "main bitiyor" (main is ending).

A custom deleter for C-style resources

Hardware drivers and many libraries are written in C: one function opens a resource and returns a handle, another function closes it. The standard FILE* and fclose pair is the best-known example. Forgetting to close is just like a memory leak: the port stays open and the next program cannot open it. You can tell a unique_ptr to call your function instead of delete:

#include <iostream>
#include <memory>

// C tarzi surucu API'si (ornek). Gercekte bir kutuphaneden gelir.
struct Port { int numara; };

Port* portAc(int numara) {
    std::cout << "COM" << numara << " acildi\n";
    return new Port{numara};
}
void portKapat(Port* p) {
    std::cout << "COM" << p->numara << " kapandi\n";
    delete p;
}
void portYaz(Port* p, const char* metin) {
    std::cout << "COM" << p->numara << " <- " << metin << '\n';
}

using PortPtr = std::unique_ptr<Port, decltype(&portKapat)>;

void olcumGonder(int numara, bool hata) {
    PortPtr port(portAc(numara), &portKapat);
    portYaz(port.get(), "V=230");
    if (hata) {
        std::cout << "hata: erken donus\n";
        return;                         // portKapat yine cagrilir
    }
    portYaz(port.get(), "I=1.2");
}

int main() {
    olcumGonder(3, false);
    olcumGonder(4, true);
    return 0;
}
COM3 acildi
COM3 <- V=230
COM3 <- I=1.2
COM3 kapandi
COM4 acildi
COM4 <- V=230
hata: erken donus
COM4 kapandi

The second parameter of std::unique_ptr<Port, decltype(&portKapat)> is the type of the deleter; decltype(&portKapat) means "the type of a pointer to the portKapat function". Because it is long, we gave it a short name with using. port.get() returns the raw pointer inside but keeps ownership; this is the right way to pass a handle to C functions. A wrapper like this is the cleanest example of how RAII applies to resources other than memory.

shared_ptr cycles and weak_ptr

A distribution panel holds its circuits, and each circuit wants to know the panel it belongs to. If both hold each other with shared_ptr, the panel keeps the circuit's counter at 1 and the circuit keeps the panel's; even after the last outside pointer is gone, the counters do not reach zero and neither is deleted. The fix is to make the link in the back direction a std::weak_ptr. A weak_ptr watches an object but does not increase its counter.

#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Pano;

struct Devre {
    std::string ad;
    std::weak_ptr<Pano> pano;            // geri baglanti: sahiplik YOK
    explicit Devre(std::string a) : ad(std::move(a)) {}
    ~Devre() { std::cout << "Devre " << ad << " silindi\n"; }
};

struct Pano {
    std::string ad;
    std::vector<std::shared_ptr<Devre>> devreler;
    explicit Pano(std::string a) : ad(std::move(a)) {}
    ~Pano() { std::cout << "Pano " << ad << " silindi\n"; }
};

int main() {
    {
        auto pano = std::make_shared<Pano>("ADP-1");
        auto aydinlatma = std::make_shared<Devre>("aydinlatma");
        aydinlatma->pano = pano;
        pano->devreler.push_back(aydinlatma);

        if (auto p = aydinlatma->pano.lock()) {
            std::cout << aydinlatma->ad << " -> " << p->ad << '\n';
        }
        std::cout << "pano sayaci: " << pano.use_count() << '\n';
    }
    std::cout << "blok bitti\n";
    return 0;
}
aydinlatma -> ADP-1
pano sayaci: 1
Pano ADP-1 silindi
Devre aydinlatma silindi
blok bitti

You cannot reach the object behind a weak_ptr directly; first you ask for a temporary shared_ptr with lock(). If the object is still alive you get a full pointer, if it has been deleted an empty one; the if (auto p = ...) pattern tells the two apart. The counter of 1 proves that the circuit does not own the panel. When the block ended, the panel was deleted, and since the panel's vector was the circuit's last owner, it deleted the circuit. If you make the Devre::pano member a shared_ptr and run the program again, you will see that the "silindi" (deleted) lines never appear.

Which one, and when?

SituationChoice
The object has a single, clear ownerstd::unique_ptr (the default choice)
Several places must keep the object alive and it is not clear who lets go laststd::shared_ptr
You want to watch the object but must not extend its lifestd::weak_ptr
The function only uses the objectconst T& or T&; T* if it "might not be there"

When in doubt, start with unique_ptr. Converting it to a shared_ptr later is easy: the line std::shared_ptr<Sensor> s = std::move(tekil); compiles. The reverse is not possible; you cannot bring a shared object back to single ownership. Also, because the shared_ptr counter is designed to be updated safely from several threads, every copy has a small cost; rather than passing it by value for no reason, pass const std::shared_ptr<T>& or simply a reference to the object.

Common mistakes

  • Making two smart pointers from the same raw pointer. Sensor* ham = new Sensor(...); std::shared_ptr<Sensor> a(ham); std::shared_ptr<Sensor> b(ham); creates two separate counters, and the object is deleted twice. Always create objects with make_unique or make_shared; if you need a second owner, copy the existing shared_ptr.
  • Thinking release() is reset(). reset() deletes the object and empties the pointer. release() gives up ownership without deleting the object and returns the raw pointer; if you do not use the returned value, you have a leak.
  • Not checking the result of lock(). If the watched object has been deleted, lock() returns an empty pointer; using it with * without a check dereferences nullptr.

Exercise

A motor drive wants to watch the motor it controls, but it must not interfere with the motor's lifetime. The Motor struct holds a devir (speed) value and prints "Motor silindi" (motor deleted) in its destructor. The Surucu (drive) struct holds the motor with a weak_ptr; its durumYaz() method prints the speed if the motor is alive and "Motor yok" (no motor) if it is not. Create the motor with make_shared, print the status, then let go of the motor's only owner with reset() and print the status again. Show the result of expired() at each step too.

Hint: expired() returns true if the watched object has been deleted. If you are going to use the object anyway, use lock() rather than expired(): it removes the chance of the object being deleted between the check and the use. To print true/false, use std::boolalpha.

Solution

#include <iostream>
#include <memory>

struct Motor {
    int devir = 1450;
    ~Motor() { std::cout << "Motor silindi\n"; }
};

struct Surucu {
    std::weak_ptr<Motor> motor;
    void durumYaz() const {
        if (auto m = motor.lock()) {
            std::cout << "Devir: " << m->devir << " d/dk\n";
        } else {
            std::cout << "Motor yok\n";
        }
    }
};

int main() {
    auto motor = std::make_shared<Motor>();
    Surucu surucu;
    surucu.motor = motor;

    surucu.durumYaz();
    std::cout << "expired: " << std::boolalpha << surucu.motor.expired() << '\n';

    motor.reset();                      // tek sahip birakti -> motor silinir
    surucu.durumYaz();
    std::cout << "expired: " << surucu.motor.expired() << '\n';
    return 0;
}
Devir: 1450 d/dk
expired: false
Motor silindi
Motor yok
expired: true

The drive watched the motor without extending its life: as soon as reset() was called, the motor was deleted and the drive noticed it safely.

In short, unique_ptr expresses a single owner, shared_ptr shared ownership and weak_ptr watching without ownership; a custom deleter brings the same safety to C resources. In the next lesson we will use lambdas and STL algorithms in depth to do more powerful work on data.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. A function will only read a sensor object and write a report; it will not store or delete the object. Which parameter type fits best?
2. After the line auto b = std::move(a); (a and b are std::unique_ptr), which statement is true?
3. A panel holds its circuits with shared_ptr. Why should the circuits' link back to the panel be a weak_ptr?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.