0

How do I initialize DefenseThread so that it will start executing Defend()? I have seen a lot of examples on how to do it from a .cpp file without a header, but non with.

void CommandDefend::DefendStart()

Gets the following error:

'&' requires I-value

Header:

#pragma once

#include <thread>

class CommandDefend : public ICommand
{
public:
CommandDefend();
~CommandDefend();

private:
thread* DefenseThread;

/// <summary>
/// Starts the commands execution.
/// </summary>
void DefendStart();

/// <summary>
/// Does the actual defending.
/// </summary>
void Defend();
};

CPP:

#include "stdafx.h"
#include "CommandDefend.h"


void CommandDefend::DefendStart()
{//ERROR HERE!!!!!!
    DefenseThread = new thread(&CommandDefend::Defend);

}

void CommandDefend::Defend()
{
}
SneakyTactician
  • 130
  • 1
  • 14
  • 1
    it doesnt have anything to do with or without header. THe problem is that your thread is destroyed when `DefendStart` returns – 463035818_is_not_an_ai Jul 14 '17 at 14:34
  • What is your question? 'I need to do this' OK, so does this code not achieve that? Why not? What happens instead? – underscore_d Jul 14 '17 at 14:47
  • Edited the question to include my compiler error. – SneakyTactician2 Jul 14 '17 at 14:51
  • What line of code produces that error? I don't see anything here that looks like it would. When you post code, you should post a [mcve] – xaxxon Jul 14 '17 at 14:53
  • Don't post just part of the error. No compiler would report an error without telling you _where_ it occurred. – underscore_d Jul 14 '17 at 14:55
  • void CommandDefend::DefendStart() {//ERROR HERE!!!!!! DefenseThread = new thread(&CommandDefend::Defend); } – SneakyTactician2 Jul 14 '17 at 14:57
  • so it's a duplicate of [Start thread with member function](https://stackoverflow.com/questions/10673585/start-thread-with-member-function) Please see there how to call the `thread` constructor correctly, and if that fixes your problem, mark your question as a duplicate of that one. – underscore_d Jul 14 '17 at 15:01
  • Nope, I have already seen that. The question is not the same, as the class is not defined with a header file, like my class is. – SneakyTactician2 Jul 14 '17 at 15:06
  • I don't believe that makes any difference at all, nor have you explained why you think it does (hint: if you implemented your class without a header, this syntax still would not work). edit: LOL, and now you've accepted a duplicate answer that says the same thing. I don't even. – underscore_d Jul 14 '17 at 15:08

1 Answers1

2

If you replace

DefenseThread = new thread(&CommandDefend::Defend);

with

DefenseThread = new thread(&CommandDefend::Defend, this);

it should work, because it's the way how I initialize class members of type std::thread (while they are not pointers).

olha
  • 2,132
  • 1
  • 18
  • 39