RAII : gestion automatique d'une ressource

Exemple de démarrage, à remplacer par vos propres extraits : un descripteur de fichier POSIX encapsulé dans une classe dont le destructeur garantit la libération, avec sémantique de déplacement et copie interdite.

#include <fcntl.h>
#include <unistd.h>

#include <stdexcept>
#include <utility>

class FileDescriptor {
public:
    explicit FileDescriptor(const char* path)
        : fd_(::open(path, O_RDONLY)) {
        if (fd_ < 0) {
            throw std::runtime_error("ouverture impossible");
        }
    }

    FileDescriptor(const FileDescriptor&) = delete;
    FileDescriptor& operator=(const FileDescriptor&) = delete;

    FileDescriptor(FileDescriptor&& other) noexcept
        : fd_(std::exchange(other.fd_, -1)) {}

    FileDescriptor& operator=(FileDescriptor&& other) noexcept {
        if (this != &other) {
            close_if_open();
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }

    ~FileDescriptor() { close_if_open(); }

    int get() const noexcept { return fd_; }

private:
    void close_if_open() noexcept {
        if (fd_ >= 0) {
            ::close(fd_);
        }
    }

    int fd_;
};

← Tous les exemples