LoginSignup
10
5

More than 5 years have passed since last update.

スレッドへの参照渡し

Posted at

スレッドに参照を渡す

おはようございます。
やってますか?C++の参照渡し。

C++でもC言語同様ポインタを使用できますが、C++で追加された参照渡しをフル活用しましょう。
C++でC言語のようなポインタ渡しをするとコンパイラには怒られなくても先輩上司に怒られます。

std::ref()を使え

スレッドに呼び出し元関数で使用している値の参照を渡すときはstd::ref()を使う。

hoge.cpp
#include <iostream>
#include <thread>

void hogeMethod( int& param )
{
    param = 100;
}

int main( void )
{
    int param = 0;
    std::thread t1( hogeMethod, std::ref(param) );
    t1.join();

    std::cout << param << std::endl;

    return 0;
}

出力結果

100

まとめ

c++を始めたばっかの頃、呼び出し先関数のパラメータに&を付ければ参照渡しになるんじゃないの!??って混乱してました。
色々あるんですね。

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5