Home  >  Article  >  Backend Development  >  Why Can\'t I Pass Non-Const References to `std::async`?

Why Can\'t I Pass Non-Const References to `std::async`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 06:32:30806browse

Why Can't I Pass Non-Const References to `std::async`?

Passing Non-Const References to std::async

In std::async, passing a non-const reference as an argument results in an error. This is a deliberate design choice.

Rationale

Determining whether a function object accepts its arguments by reference is not always feasible. Thus, std::async must either copy all arguments or accept them by reference. Copying arguments ensures safety as they cannot become dangling or cause race conditions.

Exception: std::ref

To allow non-const reference parameters, std::ref can be used. This is an explicit opt-in to potentially dangerous reference semantics, requiring careful handling of dangling references and race conditions.

The above is the detailed content of Why Can\'t I Pass Non-Const References to `std::async`?. 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