gpt4 book ai didi

c++ - '&' : illegal operation on bound member functions expression Thread

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:16 24 4
gpt4 key购买 nike

我试图在一个线程中运行一个成员函数,但是我在绑定(bind)成员函数上得到错误非法操作,我不确定我做错了什么。我希望有人可以向我解释我做错了什么以及为什么会出现此错误,并举例说明如何修复它。代码如下所示:

void GameWorld::SetupWorld()
{
// create the window (remember: it's safer to create it in the main thread due to OS limitations)
RenderWindow window(VideoMode(800, 600), "OpenGL");

// deactivate its OpenGL context
window.setActive(false);

// launch the rendering thread
Thread thread(&Render, &window);//This line gives the error
thread.launch();
}

void GameWorld::Render(RenderWindow* window)
{
Texture texture;
Sprite sprite;

if (!texture.loadFromFile("sprite.png"))
{

}

sprite.setTexture(texture);

// the rendering loop
while (window->isOpen())
{

// clear the window with black color
window->clear(Color::White);

// draw everything here...
window->draw(sprite);

// end the current frame
window->display();
}
}

最佳答案

你有一个严重的案例 undefined behavior从将指向局部变量的指针传递给线程。

一旦函数返回,该变量将超出范围,对象将被破坏,留下指向未分配内存的指针。


如果 Render 函数不是static,你也会遇到问题,因为非静态成员函数有一个隐藏的第一个参数,它变成了 this成员函数内部的指针。编译器可能会提示这个问题。


第三个可能的问题可能是,一旦 SetupWorld 函数返回,您的 thread 变量将超出范围并被破坏。根据您使用的线程框架,它可能会意外终止线程。

关于c++ - '&' : illegal operation on bound member functions expression Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029818/

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