String and Array

Hey guys,

I’m getting access violations. In particular:

class StringCopyTest
{
public:
	juce::String variable;
};

// 1 > ok
{
	StringCopyTest s1, s2;
	s1.variable = "Hello World";
	s2 = s1;
}

// 2 > ok
{
	std::vector<StringCopyTest> v1, v2;
	StringCopyTest s;
	s.variable = "Hello World";
	v1.push_back(s);
	v2 = v1;
}

// 3 > fails
{
	juce::Array<juce::String> a1, a2; 
	a1.add(T("Helo World"));
	a2 = a1;
}

// 4 > fails
{
	juce::Array<StringCopyTest> a1, a2;
	StringCopyTest s;
	s.variable = "Hello World";
	a1.add(s);
	a2 = a1;
}

Specifically any class that has String and is contained in Array will give an exception on copying the array.

Is this a bug? Am I missing something? Help! :slight_smile: I know there’s the StringArray which solves case 3, but case 4 isn’t helped by StringArray…

  • Bram

Array is only for simple types like int, char, bool, (MyClass *). For complex types that should be deleted with the array, use OwnedArray. For Strings use StringArray. Best is to read the JUCE docs for all this.

I’m curious and don’t understand the exact mechanics of this. I think I heard it’s because it uses malloc for the sizeof(…) the datatype, but I’m not sure why this excludes “complex types”. What makes a type complex?

Well think about it:

Is allocating space with malloc() for a class the same as using new operator for a class? … it isn’t. So Array will only work with simple types or structs (ok, complex types was not a good word choice from my side, let’s correct it to classes).

malloc won’t call the constructor, so no variables will be initialized. If it’s a class with virtual functions, the vtable won’t be setup either.

What a head-smacking moment. Of course malloc wouldn’t call a constructor. Well at least I’ll never forget, now… :shock:
Thanks, both.