尝试调用目标函数时,尝试std :: thread会引发编译器错误

时间:2016-02-01 07:04:18

标签: c++ multithreading

下午好,

我一直试图创建一些线程来对某些数据执行更新循环,但是当我尝试调用std::thread newThread(updateLoop)时,我得到了一个通用编译器错误:

"没有构造函数的实例&#st; :: thread :: thread'匹配参数列表,"

和MS VC ++ 2015错误C3867:

"' projectileHandeler :: updateLoop&#39 ;:非标准语法;使用'&'创建指向成员的指针"

当我尝试遵循C3867中的建议时,将线程调用更改为std::thread newThread(&updateLoop),编译器将抛出MS VC ++ C2276:

"'&':对绑定成员函数表达式的非法操作。"

在阅读编译器错误资源并尝试std::thread newThread(this->updateLoop)std::thread newThread(*updateLoop)std::thread newThread(*&updateLoop)之类的变体之后[我感到非常绝望...我知道最后一个不是'去工作...],我仍然得到各种错误,涉及不正确的引用或我的调用std :: thread不匹配任何重载。

请问有谁能对我的错误有所了解吗?

当然,代码:

ProjectHandeler.cpp: 注意:标准库线程和向量头包含在stdafx.h中

#include "stdafx.h"
#include "DataTypes.h"
#include "ProjectHandeler.h"

projectileHandeler::projectileHandeler(projectile* inputList[], int inputCount) {
    for (int i = 0; i < inputCount; i++) {
        projectileList.push_back(*inputList[i]);
    }

    //Create 1 thread for each 10 projectiles.
    for (unsigned int i = 0; i < projectileList.size(); i++) {
        std::thread thread(updateLoop);
        thread.detach();
    }
}

void projectileHandeler::updateLoop() {
//Do stuff
}

ProjectHandeler.h:

#pragma once
#ifndef PROJECTILE_H
#define PROJECTILE_H

#include "stdafx.h"
#include "DataTypes.h"


#endif

class projectileHandeler {
private:

    std::vector<projectile> projectileList;

    void updateLoop();

public:

    projectileHandeler(projectile* inputList[], int inputCount);

    ~projectileHandeler();

    projectile* getProjectilePointerFromId(unsigned int id);

    //Make the NPC and Player handeler friend classes

};

1 个答案:

答案 0 :(得分:0)

找到解决方案......虽然我仍然无法使原始版本起作用,但是研究Niall建议的帖子时使用lambdas来预先形成线程,这会绕过成员函数引用的需要。

因此std::thread newThread(updateLoop);变为std::thread([this] { updateLoop(); });

更高版本还具有匿名启动线程的优点,允许循环执行而无需重命名任何内容。

那就是说,我仍然会理解原始代码无法编译的原因。通读后,我在建议的重复帖子中找不到具体案例的答案。