Home > Article > Backend Development > 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!