1

I have the next code:

#include <iostream>
#include <Windows.h>
#include <thread>
#include <string>

void func(std::string& str)
{
    std::string to_change("Bye...");
    std::cout << "From func: " << str << std::endl;
    str.swap(to_change);
}

int main()
{
    std::string Meeting = "Hi!";
    std::thread t1(func, Meeting);
    t1.join();

    std::cout << "From main: " << Meeting << std::endl;


    Sleep(20000);
    return 1;
}

The output is:

From func: HI

From main: HI

But if I do this type of moving by reference:

std::ref(Meeting)

Then the output goes:

From func: HI

From main: Bye...

What are the difference between sending the both reference types?

timrau
  • 22,054
  • 4
  • 51
  • 63
ERV ERV
  • 11
  • 2
  • The code you posted doesn't compile with gcc or clang, which leads me to believe that it compiles under (presumably) MSVC due to some nonstandard extensions. – Daniel Kamil Kozar Feb 05 '17 at 16:51
  • http://en.cppreference.com/w/cpp/thread/thread/thread – chris Feb 05 '17 at 16:52
  • Might not be the best link for a duplicate. But the answer still applies: thread always intentionally copies the passed thread arguments. – AnT Feb 05 '17 at 16:52

0 Answers0