首頁 > 後端開發 > C++ > 為什麼透過引用 std::thread 傳遞物件會呼叫複製建構子?

為什麼透過引用 std::thread 傳遞物件會呼叫複製建構子?

Linda Hamilton
發布: 2024-11-15 08:17:02
原創
393 人瀏覽過

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));
登入後複製

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.

以上是為什麼透過引用 std::thread 傳遞物件會呼叫複製建構子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板