首頁 >後端開發 >C++ >為什麼「std::thread」在按引用傳遞時會呼叫複製建構子?

為什麼「std::thread」在按引用傳遞時會呼叫複製建構子?

Barbara Streisand
Barbara Streisand原創
2024-11-15 10:08:021035瀏覽

Why Does `std::thread` Appear to Call the Copy Constructor When Passing by Reference?

std::thread Passes by Value: Copy Constructor Called

Problem:
When passing arguments to a thread using std::thread, passing by reference appears to be calling the copy constructor. This is observed in a case where the passed class has a disabled copy constructor.

Explanation:
By default, std::thread takes its arguments by value. Despite the appearance of a reference in the function signature, the argument is actually copied into the thread object. In the given example, the Log class has its copy constructor disabled, hence the compiler error when passing it by reference.

Solution: Reference Semantics with std::reference_wrapper:
To achieve reference semantics, use std::reference_wrapper to wrap the object and pass it to the thread. This effectively passes a reference to the original object without creating a copy:

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

Thread Function Declarations:
To use std::ref, the corresponding thread function must be modified to accept a std::reference_wrapper:

static void session(tcp::socket *sock, std::reference_wrapper<Log> logger)
{
    std::cout << " session () " << std::endl;
}

Lifetime Management:
It's important to ensure that the passed object (in this case, logger) outlives the thread to avoid dangling references.

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn