Skip to content

Instantly share code, notes, and snippets.

@daparic
Last active June 7, 2023 04:38
Show Gist options
  • Select an option

  • Save daparic/0eac0a129dce6d9e2374eb4d541699fc to your computer and use it in GitHub Desktop.

Select an option

Save daparic/0eac0a129dce6d9e2374eb4d541699fc to your computer and use it in GitHub Desktop.

std::thread inside a loop using push_back

#include <iostream>
#include <vector>
#include <thread>

int main(int argc, char* argv[]) {
    std::vector<std::thread> v;
    for (int i = 0; i < 3; i++) {
        v.push_back(std::thread([] {
            // Do some work inside the thread
        }));
    }
    for (std::thread& thread : v) {
        thread.join();
    }
    for (std::thread& thread : v) {
        thread.detach();
    }
    return 0;
}

std::thread inside a loop using emplace_back

#include <iostream>
#include <vector>
#include <thread>

int main(int argc, char* argv[]) {
    std::vector<std::thread> v;
    for (int i = 0; i < 3; i++) {
        v.emplace_back([] {
            // Do some work inside the thread
        });
    }
    for (std::thread& thread : v) {
        thread.join();
    }
    return 0;
}

non-copyable

class NonCopyable {
public:
    NonCopyable() = default;
    ~NonCopyable() = default;

    // Delete the copy constructor and copy assignment operator
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;

    // Other member functions
    void doSomething() {
        // Code for the member function
    }
};

Check file exists

#include <fstream>

bool fileExists(const std::string& filePath) {
    std::ifstream file(filePath);
    return file.good();
}

try/catch

#include <new>
...
    try {
        int* myArray = new int[1000000000000];  // Attempt to allocate a very large array
        // Use the allocated memory here
        delete[] myArray;
    }
    catch (const std::bad_alloc& e) {
        // std::cout << "Memory allocation failed: " << e.what() << std::endl;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment