Below is a simple C++/CLI example.
// TestCLR.cpp : main project file.
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
System::Collections::Generic::List<String^> TestList;
for(int i = 0; i < 10 ; i++)
{
TestList.Add(i.ToString());
}
for each(String^% st in TestList)
{
st += "TEST";
Console::WriteLine(st);
}
for each(String^ st in TestList)
{
Console::WriteLine(st);
}
return 0;
}
I get the following output:
0TEST
1TEST
2TEST
3TEST
4TEST
5TEST
6TEST
7TEST
8TEST
9TEST
0
1
2
3
4
5
6
7
8
9
In short, the values inside TestList do not change even though I am using a tracking pointer to change its value to “TEST”.
What should I modify in the above snippet so that the value is permanently changed?
You’ve got a
System::Collections::Generic::List, which uses a property to access items. You can’t bind a tracking reference to a property, you end up with a reference to a temporary copy of the value instead.That code would work for an array, but
foreachcan’t be used to mutate elements in-place in a container. You’ll need a for loop, because you need the index to overwrite list elements:Didn’t you get a compiler warning telling you that you were binding a non-const reference to a temporary object?