予想通り、この問題はメモリの不適切な使用が原因であることが判明しました。次の例が正しいと 99% 確信しています。それはほとんど疑似コードなので、明らかにコンパイルされません。
アップデート:
nusi のおかげで 3 番目のソリューションを追加しました。
間違った方法 (スタック メモリを使用):
std::map<int, MyType1> myMap;
void firstFunctionRunFromThread1()
{
MyType1 mt1;
mt1.Test = "Test 1";
myMap[0] = mt1;
}
void onlyFunctionRunFromThread2()
{
MyType1 mt1 = myMap[0];
// This actually does print "Test 1", so the memory is being accessed.
std::cout << mt1.Test << endl;
/* However, because we're using stack memory here, this value is lost
* when we go back to thread #1. */
mt1.Test = "Test 2";
}
void secondFunctionFromThread1()
{
MyType1 mt1 = myMap[0];
// This will actually print out "Test 1", where "Test 2" is expected!
std::cout << mt1.Test << endl;
}
複雑で正しい方法 (ヒープメモリを使用) :
スタック メモリを使用する簡単な方法も参照してください。
std::map<int, MyType1> myMap;
void firstFunctionRunFromThread1()
{
// Use heap memory so the memory stays allocated.
MyType1 *mt1 = new MyType1();
mt1->Test = "Test 1";
myMap[0] = *mt1;
}
void onlyFunctionRunFromThread2()
{
/* Now, get a pointer to the object; we can't use stack memory
* here because the values assigned would be lost as soon as
* we try and access them from secondFunctionFromThread1() */
MyType1 *mt1 = &myMap[0];
// As expected, this prints "Test 1"
std::cout << mt1->Test << endl;
/* Now, because we're assigning to memory on the heap, this will
* stay assigned until the entire application exits, yay! */
mt1->Test = "Test 2";
}
void secondFunctionFromThread1()
{
/* Not sure if using heap memory here is neccecary, but we'll do
* it anwyay just to play on the safe side... let me know if this
* is pointless... */
MyType1 *mt1 = &myMap[0];
// Hurray, this prints "Test 2"!!! :)
std::cout << mt1->Test << endl;
}
シンプルで正しい方法 (スタック メモリを正しく使用) :
答えてくれたnusiに感謝します。
std::map<int, MyType1> myMap;
void firstFunctionRunFromThread1()
{
MyType1 mt1;
mt1.Test = "Test 1";
myMap[0] = mt1;
}
void onlyFunctionRunFromThread2()
{
/* Using the & before the variable turns it into a reference, so
* instead of using stack memory, we use the original memory.
* NOTE: Is this explanation correct? */
MyType1 &mt1 = myMap[0];
// This actually does print "Test 1", so the memory is being accessed.
std::cout << mt1.Test << endl;
// We're assigning to the reference, so this works.
mt1.Test = "Test 2";
}
void secondFunctionFromThread1()
{
MyType1 mt1 = myMap[0];
// Prints "Test 1" as expected.
std::cout << mt1.Test << endl;
}