Last active
July 27, 2017 11:27
-
-
Save odeblic/c19f05e8a30fc5ffd7ce1e693b7cdedf to your computer and use it in GitHub Desktop.
Simple example for std::call_once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <mutex> | |
#include <functional> | |
struct Object | |
{ | |
Object(int n) : n(n) {} | |
void init() { std::call_once(initialized, [this] { std::cout << "init with n=" << n << std::endl; }); } | |
void action_1() { init(); std::cout << "action 1" << std::endl; } | |
void action_2() { init(); std::cout << "action 2" << std::endl; } | |
void action_3() { init(); std::cout << "action 3" << std::endl; } | |
int n{0}; | |
std::once_flag initialized; | |
}; | |
int main(void) | |
{ | |
Object a(10); | |
a.init(); | |
a.action_1(); | |
a.action_2(); | |
a.action_3(); | |
std::cout << "----------------" << std::endl; | |
Object b(20); | |
b.action_1(); | |
b.action_2(); | |
b.action_3(); | |
std::cout << "----------------" << std::endl; | |
Object c(30); | |
c.action_2(); | |
c.action_3(); | |
std::cout << "----------------" << std::endl; | |
Object d(40); | |
d.action_3(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment