Saturday, January 21, 2017

C++ snippets memo

hand-made scope_guard without boost scope_guard & other stuff:

std::shared_ptr<void> l(nullptr, [](void*){ system("pause"); });

example of such 'scope_guard' - temp_dir which guaranteed be deleted when out of scope:

std::string temp_filename = MyGetTempFilename();
std::shared_ptr<void> l(nullptr, [temp_filename](void*){
    boost::filesystem::remove(temp_filename);
});


thread & lambda - as for me, useful pattern - especially for unit-testing:

thread to lambda:
std::thread t([](){
    std::this_thread::sleep_for(std::chrono::seconds(1));
    system("taskkill /F /IM calc.exe");
});
t.join();


shared_ptr + placement new

std::shared_ptr<boost::interprocess::interprocess_mutex>
    placement_shared_ptr(
        new(region.get_address())boost::interprocess::interprocess_mutex,
        [](boost::interprocess::interprocess_mutex* l)
        {
            l->~interprocess_mutex();;
        }
    );


boost::thread_group replace to std::thread pattern

std::vector<std::thread> my_threads;
for (size_t i = 0; i < (size_t)threads_num; ++i)
{
    my_threads.push_back(std::thread(std::bind(&MyClass::RunThread, this,
        parameters
        )));
}
for (size_t i = 0; i < my_threads.size(); i++)
{
    my_threads[i].join();
}


.

1 comment: