gpt4 book ai didi

c++ - std::thread Visual Studio 2012 警告

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:58 25 4
gpt4 key购买 nike

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

#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))”:未调用原型(prototype)函数(是否为变量定义?)

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

最佳答案

警告告诉您,try block 中的第一行被解析为函数声明。如果您使用 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

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

关于c++ - std::thread Visual Studio 2012 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com