简体   繁体   中英

How to pass an object as reference or pointer to a thread function?

So I want to have a simple multithreaded program that can pass by reference (or as a pointer) to the thread functions. I can't seem to do it in a way that works. How would I code it correctly so that it compiles?

#include <iostream>
#include <thread>

using namespace std;

class MyClass
{
    int x;
public:
    MyClass()
    {
        x = 10;
    }
};

void foo(MyClass* c)
{
    cout << "This is it" << endl;
}

int main()
{
    MyClass c();

    thread t1(foo, &c);

    t1.join();

    return 0;
}

The thread function needs to be able to access the MyClass object in order to record and get data. Is this even possible? How can this be done?

EDIT: What I ultimately need to have happen is for any changes made to the class object 'c' in the thread to actually happen in that same instance of the object. This program will later be elaborated upon to run several threads all accessing that one instance of the MyClass object. So if there is another way to do this without using references or pointers, or whatever, please let me know!

You need to declare c as

MyClass c;

When you add the parens it looks like the declaration of a function called c that takes no parameters and returns a MyClass object; this is known as the Most Vexing Parse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM