I have this code
#include <thread> typedef struct { int a; short b; }TestStruct; void TestParamRef(const TestStruct& test) { Sleep(3000); /*Sleep to wait for the caller function end*/ TestStruct i = test; /*Test if the argument still ok*/ } void TestParamPointer(TestStruct* test) { Sleep(4000); /*Sleep to wait for the caller function end*/ TestStruct i = *test; /*Test if the argument still ok*/ } void Test() { TestStruct localTest; /*Local variable should be destroyed after this Test function end*/ localTest.a = localTest.b = 69; std::thread threadRef(TestParamRef, localTest); threadRef.detach(); /*Bye bye thread*/ localTest.a = 6969; std::thread threadPointer(TestParamPointer, &localTest); threadPointer.detach();/*Bye bye thread*/ localTest.b = 696969; } int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { Test(); /*Put break point here*/ return 0; }
As you can see in the code, I'm trying to check what happens if I pass a local variable to a stream, and this local variable is destroyed before the stream is used. And I find out that TestParamPointer gets a ridiculous value (perhaps because it now points to the basket value), but TestParamRef still gets the correct value.
So, I wonder if the thread really stores its argument in its own memory? I thought that when I use 'const TestStruct & test', the function will not copy the entire parameter, but reuse this parameter (I use this when the parameter is quite large - like sql table data). So how does it work? This is safe when I pass a local variable to the stream.
source share