Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

80%
+6 −0
Q&A Confusion about using std::async with class member function

On the cppreference page for std::async, there's an example where the object for a PMF invocation is passed by value. So clearly, that is okay; in fact there is nothing on the cppreference page say...

posted 4y ago by C. K. Young‭

Answer
#1: Initial revision by user avatar C. K. Young‭ · 2020-12-26T03:33:24Z (almost 4 years ago)
On the [cppreference page for `std::async`](https://en.cppreference.com/w/cpp/thread/async), there's an example where the object for a PMF invocation is passed by value. So clearly, that is okay; in fact there is nothing on the cppreference page saying it has to be a reference.

However, in your example, you've only got passing by value (`x`) and passing by pointer (`&x`); you can also pass by reference using `std::ref(x)`. Here, I modified your example to show this to better effect:

```cpp
#include <future>
#include <iostream>
#include <thread>

struct X {
    X() noexcept {
        std::cerr << "X::X()\n";
    }

    X(X const&) noexcept {
        std::cerr << "X::X(X const&)\n";
    }

    ~X() noexcept {
        std::cerr << "X::~X()\n";
    }

    void add(int num1, int num2) noexcept {
        int result = num1 + num2;

        std::cout << "The result is " << result << "\n";
    }
};

int main() {
    X x;
    std::cerr << "\nBy reference:\n";
    std::async(&X::add, std::ref(x), 42, 5).get();
    std::cerr << "\nBy pointer:\n";
    std::async(&X::add, &x, 42, 5).get();
    std::cerr << "\nBy value:\n";
    std::async(&X::add, x, 42, 5).get();
    std::cerr << "\nAll done!\n";
}
```