My assumption was that my getVar() makes a copy (copy constructor which would create whole new instances of the contained data or something similar) of std::var. That’s why I named the variable it got stored in numbers_copy. But my comment above it simply said “Get the same var” which should have probably read “Copy the same var”.
That being said, I made a slightly modified version of the same test, which gives odd results:
juce::var m_var;
MainComponent()
{
// Create our juce::var
juce::Array<juce::var> numbers;
for (int i = 0; i < 10; i++)
numbers.add(i);
m_var = juce::var(numbers);
// Copy the same var, modify it
juce::var numbers_copy = getVar();
numbers_copy[5] = 123;
// Print contents of both juce::vars
for (int i = 0; i < 10; i++)
std::cout << juce::String(m_var[i]) << ", ";
std::cout << std::endl;
for (int i = 0; i < 10; i++)
std::cout << juce::String(numbers_copy[i]) << ", ";
std::cout << std::endl;
// Test if both juce::vars are identical or not (they shouldn't be)
for (int i = 0; i < 10; i++)
jassert(m_var[i] == numbers_copy[i]);
// Other stuff
setSize(600, 400);
}
juce::var getVar()
{
return m_var;
}
The output is this:
0, 1, 2, 3, 4, 123, 6, 7, 8, 9,
0, 1, 2, 3, 4, 123, 6, 7, 8, 9,
Meaning, when I change numbers_copy[5], it seems that also the m_var[5] gets changed the same time. This happens regardless of me getting the std::var from getVar(), which should make a copy.
I might be missing something very obvious here, as I just woke up and I haven’t had my head cleared from the nights sleep, but at the moment something seems off here.
I think this is something I’ve ran into before which has caused me some confusion to how to use std::var and what’s really going on with them.
So I’m confused:
Is that behavior intended or not? It doesn’t feel consistent at all. I would expect, that if you get a copy of the std::var in one way, the other ways of getting the std::var would also make a copy. But the above test indicates otherwise.