英文:
Passing values to a thread with _beginthread and avoiding C-style casts?
问题
#include <windows.h>
#include <process.h>
#include <iostream>
void myThread(void* threadParams)
{
int* x = static_cast<int*>(threadParams);
std::cout << "*x: " << *x;
}
int main()
{
BOOL bValue2 = TRUE;
_beginthread(myThread, 0, static_cast<void*>(&bValue2));
Sleep(10000);
}
英文:
My program creates a thread but I'm getting a "Don't use C-style casts" in my code analysis with Visual Studio.
#include <windows.h>
#include <process.h>
#include <iostream>
void myThread(void * threadParams)
{
int* x = (int*)threadParams;
std::cout << "*x: " << *x;
}
int main()
{
BOOL bValue2 = TRUE;
_beginthread(myThread, 0, (LPVOID)&bValue2);
Sleep(10000);
}
I tried static_cast<LPVOID>&bValue2
but it gives an error.
What is the proper format for casting in _beginthread
?
答案1
得分: 3
以下是您要翻译的代码部分:
#include <thread>
#include <string>
#include <iostream>
void my_thread_function(const std::string& hello, int x)
{
std::cout << hello << "\n";
std::cout << x << "\n";
}
int main()
{
int x{ 42 };
std::string hello{ "hello world" };
std::thread thread{ [=] { my_thread_function(hello, x); } }; // [=] capture x and hello by value
thread.join(); // wait for thread to complete (no need to sleep);
return 0;
}
如果您需要进一步的帮助,请随时提问。
英文:
Here is an example :
// no need to inlcude OS specific headers
// thread support is in since C++11
// https://en.cppreference.com/w/cpp/thread/thread
// https://en.cppreference.com/w/cpp/language/lambda
#include <thread>
#include <string>
#include <iostream>
void my_thread_function(const std::string& hello, int x)
{
std::cout << hello << "\n";
std::cout << x << "\n";
}
int main()
{
int x{ 42 };
std::string hello{ "hello world" };
std::thread thread{ [=] { my_thread_function(hello, x); } }; // [=] capture x and hello by value
thread.join(); // wait for thread to complete (no need to sleep);
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论