std::thread Visual Studio 2012 Warning

std::thread Visual Studio 2012 Warning

本文关键字:2012 Warning Studio Visual thread std      更新时间:2023-10-16

我正在尝试了解如何使用Visual Studio 2012使用新的std::线程。我正在尝试编译以下代码。

#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;
}

我得到一个警告说警告C4930: 'scoped_thread t(std::thread (__cdecl *)(local_functor))':未调用原型函数(是否打算定义变量?)

是的,这是一个变量定义。我该怎么做呢?

该警告告诉您,try块中的第一行被解析为函数声明。如果使用c++ 03初始化风格,有时会发生这种情况。使用统一初始化:

scoped_thread t{std::thread{local_functor{some_local_state}}};

此外,在scoped_thread构造函数中缺少&:

explicit scoped_thread(std::thread && t): t_(std::move(t))
//                                 ^-- use r-value ref

PS:如果你的编译器不支持统一的初始化,将初始化器包装到另一对括号中:scoped_thread t((std::thread(local_functor(some_local_state))));

您无意中发现了最令人烦恼的解析。

您可以使用统一的初始化语法来解决它:

scoped_thread t{std::thread(local_functor(some_local_state))};