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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 12:18:301001browse

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>

Compilers report an error with this code:

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

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!

Statement:
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