I am trying to understand how to use the new std::thread using Visual Studio 2012. I am trying to compile the following code.
#include <iostream>
#include <thread>
class scoped_thread
{
std::thread t_;
public:
explicit scoped_thread(std::thread & t): t_(std::move(t))
{
if(!t_.joinable())throw std::logic_error("No thread");
}
~scoped_thread()
{
t_.join();
}
private:
scoped_thread(scoped_thread const &);
scoped_thread & operator=(scoped_thread const &);
};
struct local_functor
{
int& i_;
local_functor(int & i):i_(i){}
void operator()()
{
while(i_ < 1e5)i_++;
}
};
// can potentially throw exceptions
void callAnotherFunc()
{
std::cout << "this function can throw an exception" << std::endl;
// try (un)commenting the line below and see the behaviour
throw std::out_of_range("WTF2");
}
int main()
{
int some_local_state = 0;
try
{
scoped_thread t(std::thread(local_functor(some_local_state)));
callAnotherFunc();
std::cout << "Proper exit of function" << std::endl;
}
catch(const std::exception & e)
{
std::cout << e.what() << " exception occurred!" << std::endl;
}
catch(...)
{
std::cout << "Unhandled exception!" << std::endl;
}
return 0;
}
I am getting a warning that says warning C4930: 'scoped_thread t(std::thread (__cdecl *)(local_functor))': prototyped function not called (was a variable definition intended?)
Yes, it was a variable definition that was intended. How am I supposed to do that?
The warning tells you, that the first line in your try block is parsed as a function declaration. That happes sometimes if you use C++03 initialization style. Use uniform initialization instead:
scoped_thread t{std::thread{local_functor{some_local_state}}};
In addition, you have a missing &
in the scoped_thread constructor:
explicit scoped_thread(std::thread && t): t_(std::move(t))
// ^-- use r-value ref
PS:
If your compiler does not support uniform initialization, wrap the initializer into another pair of brackets: scoped_thread t((std::thread(local_functor(some_local_state))));
You stumbled upon the most vexing parse.
You could solve it by using the uniform initialization syntax:
scoped_thread t{std::thread(local_functor(some_local_state))};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With