265818 (18) [Avatar] Offline
#1
template <typename F>
class lazy_val {
private:
F m_computation;
mutable decltype(m_computation()) m_cache;
mutable std::once_flag m_value_flag;
public:
lazy_val(F computation) : m_computation(computation) {}
lazy_val(lazy_val &&other) : m_computation(std::move(other.m_computation)) {}
operator const decltype(m_computation())& () const {
std::call_once(m_value_flag, [this] {
m_cache = m_computation();
});
return m_cache;
}
};

int main(int argc, char *argv[]) {
int number = 6;

auto val = lazy {
std::cout << "Calculating the answer..." << std::endl;
std::cout << "while the number is: " << number << std::endl;
return 42;
};

std::cout << "Lazy value defined" << std::endl;

std::cout << val << std::endl;
}


Compiling and executing:

g++ -std=c++17 lazy_valB17-withoutMutex.cpp -olazy_valB17-withoutMutex
azy value defined
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)

What am I doing wrong?

Ivan Cukic (96) [Avatar] Offline
#2
My guess is that you are missing the -pthread flag when compiling. This is something I also tend to forget smilie
265818 (18) [Avatar] Offline
#3
g++ -std=c++17 lazy_valB17-withoutMutex.cpp -lpthread -olazy_valB17-withoutMutex
./lazy_valB17-withoutMutex
Lazy value defined
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)

What else I forget to do ?
265818 (18) [Avatar] Offline
#4
Compiling in this way:
g++ -std=c++17 lazy_valB17-withoutMutex.cpp -pthread -olazy_valB17-withoutMutex

/lazy_valB17-withoutMutex
Lazy value defined
Calculating the answer...
while the number is: 6
42

I should study the differences between -lpthread and -pthread flags..

Ivan Cukic (96) [Avatar] Offline
#5
IIRC, -lpthread just links the library while -pthread also defines some macros that are used during the compilation phase. You should always use the latter.
265818 (18) [Avatar] Offline
#6
thank you very much.
I keep studying and using your excellent book