Home > Backend Development > C++ > body text

Why can\'t I pass a non-const reference to `std::async` and how do I work around it?

Mary-Kate Olsen
Release: 2024-10-28 12:18:30
Original
947 people have browsed it

Why can't I pass a non-const reference to `std::async` and how do I work around it?

Incompatibilities in Argument Passing to std::async by Reference

The inability to pass a non-const reference as an argument to std::async has perplexed developers. Consider the following example:

<code class="cpp">#include <functional>
#include <future>

void foo(int& value) {}

int main() {
    int value = 23;
    std::async(foo, value);
}</code>
Copy after login

Compilers report an error with this code:

error: no type named ‘type’ in ‘class std::result_of<void (*)(int)>()’
Copy after login

Encasing the argument in std::reference_wrapper resolves the issue, but it raises questions about the underlying mechanism.

Reasoning Behind Value-Based Argument Passing

std::async's design intentionally defaults to passing all arguments by value. This choice ensures safety, as copies of arguments cannot become dangling or exhibit race conditions.

Addressing Non-Const Reference Parameters

However, there are scenarios where passing an argument by non-const reference is necessary. This is where std::ref comes into play. std::ref allows developers to explicitly opt into the risky semantics of passing non-const references, acknowledging their understanding of the potential consequences.

The above is the detailed content of Why can\'t I pass a non-const reference to `std::async` and how do I work around it?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!