Vector get passed to a thread by val insted of by ref

I have a function :
 
void UpdateNotefications(vector <string> &Notefic)


where I change a vector...

I called it with a thread :

1
2
thread t1 (UpdateNotefications, Notefic);
			t1.detach();


though I see that inside the func, Notefic has a val, and outside, it is still empty (after the function is over)...
You have to remember that this 'thread' constructor is a function of sorts itself, so if the ".detach()" member function returns a copy of the object then that copy is what gets forwarded to your thread and passed by reference.
So what can I do ?
To pass an argument to the thread function by reference, you have to wrap it.

1
2
// thread t1 (UpdateNotefications, Notefic);
thread t1 ( UpdateNotefications, std::ref(Notefic) ) ;
I have used that, but it still didnt passed it by ref...
> but it still didnt passed it by ref...

Before you jump to conclusions, check it out by writing a small test program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <vector>
#include <thread>
#include <memory>
#include <functional>

void thread_fun( std::vector<int>& seq )
{
    std::cout << "thread: reference is to sequence at " << std::addressof(seq) << '\n' ;
    seq.insert( seq.end(), { 5, 6, 7, 8, 9 } ) ;
}

#include <iostream>

int main()
{
    std::vector<int> seq { 0, 1, 2, 3, 4 } ;
    std::cout << "main: sequence is at " << std::addressof(seq) << '\n' ;
    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;

    std::thread t( &thread_fun, std::ref(seq) ) ;
    t.join() ;

    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}

Output:
main: sequence is at 0x22fee4
0 1 2 3 4
thread: reference is to sequence at 0x22fee4
0 1 2 3 4 5 6 7 8 9
Last edited on
Thanks!
Topic archived. No new replies allowed.