I've done quite a bit of research on the new c++11 rvalue and carried over lvalue. Here is a sample of what I have found and read:
what-does-t-double-ampersand-mean-in-c11
I have also briefed myself on rvalue references
Specifically, regarding the std::thread
constructor, I found
and used one of the answers to write some simple code
#pragma once
#ifndef CONSUMER_H
#define CONSUMER_H
#include "Mailbox.h"
#include <thread>
#include <iostream>
class Consumer
{
private:
Mailbox mailbox;
std::thread consumer;
public:
Consumer(Mailbox& newMailbox);
~Consumer();
void operator()() { std::cout << consumer.get_id() << "starting\n"; }
void start();
void run();
};
Consumer::Consumer(Mailbox& newMailbox)
{
this->mailbox = newMailbox;
}
void Consumer::start()
{
consumer = std::thread(&Consumer::run, this); <-- need understanding
}
#endif
Checking the `std::thread constructor
I observe a template that uses rvalue parameters. I understand that a std::thread
can be initiated through a simple example
void run(void) {std::cout << "I'm running";}
std::thread(run);
which appears straight-forward until I am inside a class whereby I need to do the following
consumer = std::thread(&Consumer::run, this); <-- need understanding
because I learned from Jonathan Wakely that run() is a non-static member function and has to be run on an object. How is the new thread supposed to know which object to call it on if you don't tell it?
This makes some sense but the need to pass by reference the class function doesn't since I have seen A a; A&& ref = A()
possible. I'm super confused about rvalues and just want to understand why the code I wrote above is necessary to pass the function to std::thread
.
I feel certain I also don't understand variadic templates that well either which compounds my understand of the std::thread
variadic template constructor.