Strumenti Utente

Strumenti Sito


programmazione:cpp:appunti_cpp

Alcuni veloci appunti su C++

Autore: Fabio Di Matteo
Ultima revisione: 10/09/2026 13:45

Ho fatto alcune pagine simili su Rust e Go, quindi perchè non farle anche su C++. Si preferirà uno standard moderno.

Buone pratiche

Dato che il C/C++ offrono massima libertà nella gestine della memoria, possono (e non devono) essere pericolosi . Dunque ho raccolto alcune buone pratiche da tenere a mente qui: Buone pratiche di programmazione in C/C++

Prelevare parti di un path

In c++17 si possono usare:

#include <filesystem>
#include <iostream>
 
namespace fs = std::filesystem;
 
int main()
{
    fs::path percorso{"/home/utente/video/test.mp4"};
 
    std::cout << "Filename:  " << percorso.filename() << '\n';
    std::cout << "Stem:      " << percorso.stem() << '\n';
    std::cout << "Estensione:" << percorso.extension() << '\n';
    std::cout << "Directory: " << percorso.parent_path() << '\n';
}

Try/catch

try {
       ...le mie istruzioni...
    } 
    catch (const std::exception& e) {
        // Intercetta std::exception e tutte le sue classi derivate
        std::cerr << "Errore intercettato: " << e.what() << std::endl;
    } 
    catch (...) {
        // Il "catch-all" intercetta qualsiasi cosa che non sia derivata da std::exception
        std::cerr << "Errore sconosciuto: è stata lanciata un'eccezione non standard." << std::endl;
    }

Thread

Lanciare un thread e proseguire col thread principale.

std::thread mio_thread([] {
        std::cout << "Eseguito in un thread separato\n";
    });

Determinare se una porta tcp è aperta o no

La funzione ritorna true se è aperta false altrimenti.

#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
 
#include <cstdlib>
#include <chrono>
#include <thread>
 
 
bool is_port_ready(const char* host, int port) {
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0)
        return false;
 
    sockaddr_in address{};
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
 
    if (inet_pton(AF_INET, host, &address.sin_addr) != 1) {
        close(socket_fd);
        return false;
    }
 
    bool is_ready = connect(
        socket_fd,
        reinterpret_cast<sockaddr*>(&address),
        sizeof(address)
    ) == 0;
 
    close(socket_fd);
    return is_ready;
}

Si potrebbe usare così:

...
 
        std::thread server([&] {
            mioservertcp.run(); //server di esempio
        });
 
        // Attende che abbia aperto la porta
        while (!is_port_ready("127.0.0.1", 8080)) {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
 
        // A questo punto il server è raggiungibile
        std::system("xdg-open http://127.0.0.1:8080/fmt");
 
        server.join();

Il mio server tcp viene eseguito su un thread esterno e il main attende 10 millisecondi finchè la porta non sia disponibile. Quando è disponibile in questo caso lancia un browser su quell'indirizzo. Infine aspettiamo che il thread termini.

Compilare codice in base al sistema operativo

Macro per Gcc .

#if defined(_WIN32)
 
    // Windows, 32 o 64 bit
 
    #if defined(_WIN64)
        // Windows 64 bit
    #else
        // Windows 32 bit
    #endif
 
#elif defined(__ANDROID__)
 
    // Android
 
#elif defined(__linux__)
 
    // Linux non Android
 
#elif defined(__APPLE__) && defined(__MACH__)
 
    // macOS o altro sistema Darwin
 
#elif defined(__FreeBSD__)
 
    // FreeBSD
 
#elif defined(__NetBSD__)
 
    // NetBSD
 
#elif defined(__OpenBSD__)
 
    // OpenBSD
 
#elif defined(__sun)
 
    // Solaris / SunOS
 
#elif defined(_AIX)
 
    // AIX
 
#elif defined(__unix__)
 
    // Altro sistema Unix
 
#else
 
    #error "Sistema operativo non supportato"
 
#endif

Una funzione per prelevare l'emulatore di terminale di default su Gnu/Linux

Questa funzione cerca di prelevare l'emulatore di default in Gnu/Linux. Se non riesce tramite la variabile d'ambiente XDG_CURRENT_DESKTOP cerca di ripiegare su alcuni fallback. Non è sicura al 100%. Cercherò di inserire quanti piu' DE possibile.

std::string get_xterminal() {
    const char* de_env = std::getenv("XDG_CURRENT_DESKTOP");
 
    if (de_env != nullptr) {
        std::string de(de_env);
        std::transform(de.begin(), de.end(), de.begin(), ::tolower);
 
        if (de.find("gnome") != std::string::npos) return "gnome-terminal";
        if (de.find("unity") != std::string::npos) return "gnome-terminal";
        if (de.find("cinnamon") != std::string::npos) return "gnome-terminal";
        if (de.find("budgie") != std::string::npos) return "gnome-terminal";
        if (de.find("pop") != std::string::npos) return "gnome-terminal"; // Pop!_OS
        if (de.find("zorin") != std::string::npos) return "gnome-terminal"; // Zorin OS
 
        // KDE e Plasma
        if (de.find("kde") != std::string::npos) return "konsole";
        if (de.find("plasma") != std::string::npos) return "konsole";
        if (de.find("kubuntu") != std::string::npos) return "konsole";
 
        // XFCE
        if (de.find("xfce") != std::string::npos) return "xfce4-terminal";
 
        // MATE
        if (de.find("mate") != std::string::npos) return "mate-terminal";
 
        // LXQt / LXDE
        if (de.find("lxqt") != std::string::npos) return "lxterminal";
        if (de.find("lxde") != std::string::npos) return "lxterminal";
 
        // Elementary OS / Pantheon
        if (de.find("elementary") != std::string::npos) return "io.elementary.terminal";
        if (de.find("pantheon") != std::string::npos) return "io.elementary.terminal";
 
        // Deepin
        if (de.find("deepin") != std::string::npos) return "deepin-terminal";
 
        // Window Managers Wayland/Tiling
        if (de.find("sway") != std::string::npos) return "foot";
        if (de.find("hyprland") != std::string::npos) return "kitty";
        if (de.find("i3") != std::string::npos) return "alacritty";
        if (de.find("awesome") != std::string::npos) return "alacritty";
        if (de.find("bspwm") != std::string::npos) return "alacritty";
        if (de.find("dwm") != std::string::npos) return "st";
        if (de.find("openbox") != std::string::npos) return "xterm";
        if (de.find("fluxbox") != std::string::npos) return "xterm";
        if (de.find("enlightenment") != std::string::npos) return "terminology";
        if (de.find("efl") != std::string::npos) return "terminology";
    }
 
     std::vector<std::string> fallback_list = {
        "kitty", "alacritty", "foot", "st", "konsole", 
        "gnome-terminal", "xfce4-terminal", "mate-terminal","sakura", 
        "lxterminal", "tilix", "terminator", "xterm"
    };
 
    for (const auto& term : fallback_list) {
        std::string check_cmd = "which " + term + " > /dev/null 2>&1";
        if (std::system(check_cmd.c_str()) == 0) {
            return term;
        }
    }
    return "xterm";
}
programmazione/cpp/appunti_cpp.txt · Ultima modifica: 01/10/2026 12:14 da Fabio Di Matteo