std::thread Visual Studio 2012 Warning
std::thread Visual Studio 2012 Warning
我正在尝试了解如何使用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))};
相关文章:
- 变量可能尚未初始化[MIRA 2012规则9.1,强制性]
- "Warning: Comma within array index expression"但逗号分隔函数参数
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- 在 Cocos2dx 中初始化粒子效果后的警告 - "libpng warning: iCCP: known incorrect sRGB profile"
- Visual Studio C6385 warning c++
- 我需要安装什么才能获得在Windows Server 2012 R2 Standard上运行C++hello world
- 使用Visual Studio 2012编译时,此代码会给我错误,但是使用代码块就可以了
- "Warning : No return statement in function returning non-void"是什么意思?
- cuda-gdb 给出错误"warning: Cuda API error detected: cudaLaunchKernel returned (0x7)"
- Windows 2012 R2 closesocket()挂在侦听套接字上
- 编译代码时"[Warning] extra tokens at end of"
- 如何配置VS 2012的编译器来更改基本数据类型大小?
- 在 Visual Studio 2012 中未命中断点
- QT_HAS_BUILTIN warning
- 在Windows Server 2012上运行VS2019编译的应用程序需要什么?
- warning C4503 with CGAL 4.12-beta 2
- 如何修复'PCH Warning: header stop not at file scope'
- C Visual Studio 2012 Express命令窗口怪异行为
- 堆损坏对 Windows 2012 r2 服务器的影响
- std::thread Visual Studio 2012 Warning