Home > Backend Development > C++ > Why Does Passing an Object by Reference to std::thread Invoke the Copy Constructor?

Why Does Passing an Object by Reference to std::thread Invoke the Copy Constructor?

Linda Hamilton
Release: 2024-11-15 08:17:02
Original
405 people have browsed it

Why Does Passing an Object by Reference to std::thread Invoke the Copy Constructor?

std::thread: Pass by Reference Invokes Copy Constructor

Understanding the Issue

When passing objects to std::thread, arguments are typically copied into the thread, rather than being referenced. This behavior contradicts the expectation that passing by reference should avoid copy construction. The confusion stems from the distinction between references and pointers in C .

Copy Constructor and Pass by Reference

In C , passing an object by reference generally means passing its address, which is equivalent to passing a pointer. However, std::thread has a specific implementation that requires its arguments to be copied by value.

Using std::reference_wrapper

To achieve reference semantics, use std::reference_wrapper as follows:

std::thread newThread(session, &sock, std::ref(logger));
Copy after login

This way, logger is not copied, but rather its reference is passed to the thread. Note that logger must outlive the thread.

Moving Semantics

The use of std::move() is not recommended in this case because std::thread expects arguments to be copied. Moving the object would transfer ownership of its memory to the thread, which may not be desired.

If your code was previously working with std::move() but now fails, it's possible that your version of the compiler does not fully implement C 11. Consider updating your compiler for enhanced C 11 support.

The above is the detailed content of Why Does Passing an Object by Reference to std::thread Invoke the Copy Constructor?. 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