Home  >  Article  >  Backend Development  >  How to Pass C Standard Library Object References to Threads Without Compilation Errors?

How to Pass C Standard Library Object References to Threads Without Compilation Errors?

Susan Sarandon
Susan SarandonOriginal
2024-11-20 15:29:11283browse

How to Pass C   Standard Library Object References to Threads Without Compilation Errors?

Passing Object Reference Arguments to Thread Functions: Overcoming Compilation Errors

Passing references to C 11 standard library objects, such as std::ostream, to thread functions can encounter compilation issues. This is because threads, by default, copy their arguments.

To pass a reference explicitly, wrap it with std::ref or std::cref for constant references. Here's a modified version of the example provided:

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

int main() {
    std::thread t(foo, std::ref(std::cout));
    t.join(); // Wait for the thread to complete
    return 0;
}

By using std::ref, you create a reference wrapper that behaves like a value-semantics object. Multiple copies of the wrapper will refer to the same underlying reference, allowing the thread to access the std::ostream object correctly.

Remember to ensure that the object referred to remains valid throughout the thread's lifetime.

The above is the detailed content of How to Pass C Standard Library Object References to Threads Without Compilation Errors?. 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