1.

Are The Arguments Passed To A C++11 Thread's Constructor Pass By Vale Or Pass By Reference?

Answer»

Thread function arguments are ALWAYS pass by value, i.e., they are always COPIED into the internal storage for threads. Any changes made by the thread to the arguments passed does not affect the original arguments. For example, we want the "targetCity" to be modified by the thread but it never happens:

#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, targetCity);

t1.join();

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

return 0;

}

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Star City

Note that the "targetCity" variable is not modified.

Thread function arguments are always pass by value, i.e., they are always copied into the internal storage for threads. Any changes made by the thread to the arguments passed does not affect the original arguments. For example, we want the "targetCity" to be modified by the thread but it never happens:

#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, targetCity);

t1.join();

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

return 0;

}

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Star City

Note that the "targetCity" variable is not modified.



Discussion

No Comment Found