1.

How Can We Pass C++11 Thread Arguments By Reference?

Answer»

We need to use STD::REF() from the <functional&GT; header. Consider the following code snippet and associated OUTPUT.

#include "stdafx.h"

#include <string>

#include <thread>

#include <iostream>

#include <functional>

using namespace std;

void ChangeCurrentMissileTarget(string& targetCity)

{

targetCity = "Metropolis";

cout << " Changing The Target City To " << targetCity << endl;

}

int main()

{

string targetCity = "Star City";

thread t1(ChangeCurrentMissileTarget, std::ref(targetCity));

t1.join();

cout << "Current Target City is " << targetCity << endl;

return 0;

}

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Metropolis

Notice that the CHANGES to "targetCity" made by the thread was preserved once the thread exited.

We need to use std::ref() from the <functional> header. Consider the following code snippet and associated output.

#include "stdafx.h"

#include <string>

#include <thread>

#include <iostream>

#include <functional>

using namespace std;

void ChangeCurrentMissileTarget(string& targetCity)

{

targetCity = "Metropolis";

cout << " Changing The Target City To " << targetCity << endl;

}

int main()

{

string targetCity = "Star City";

thread t1(ChangeCurrentMissileTarget, std::ref(targetCity));

t1.join();

cout << "Current Target City is " << targetCity << endl;

return 0;

}

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Metropolis

Notice that the changes to "targetCity" made by the thread was preserved once the thread exited.



Discussion

No Comment Found