Home > Backend Development > C++ > Why Does Passing Object References to C Threads Cause Compilation Errors?

Why Does Passing Object References to C Threads Cause Compilation Errors?

Linda Hamilton
Release: 2024-12-03 12:10:16
Original
672 people have browsed it

Why Does Passing Object References to C   Threads Cause Compilation Errors?

Passing Object References to Thread Functions: Understanding the Challenges

In C 's std::thread interface, passing object reference arguments to thread functions can encounter compilation errors. This article explores the underlying reasons for these errors and provides solutions.

Understanding Object Reference Passing

In the provided example, an integer (k) can be passed to a thread function as follows:

void foo(int &i) {
    // Do something with i
    std::cout << i << std::endl;
}

int k = 10;
std::thread t(foo, k);
Copy after login

However, attempting to pass an ostream reference to a thread function results in a compilation error:

void foo(std::ostream &os) {
    // Do something with os
    os << "This should be printed to os" << std::endl;
}

std::thread t(foo, std::cout);
Copy after login

The Deleted Constructor

The compilation error is rooted in the fact that std::thread has a deleted constructor that prevents direct object reference passing. This is intentional, as threads should copy their arguments to avoid race conditions.

The Solution: std::ref

To pass an object reference explicitly, wrap it with std::ref (or std::cref for constant references). This solution ensures that a copy of the reference is passed to the thread function, ensuring safety:

std::thread t(foo, std::ref(std::cout));
Copy after login

Preserving Object Lifetime

It is crucial to note that the reference wrapper only contains a reference to the object. Hence, it is essential to ensure that the object remains alive throughout the thread's execution. Failure to do so will result in undefined behavior.

The above is the detailed content of Why Does Passing Object References to C Threads Cause Compilation Errors?. 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