Could someone explain the rules for Strings?

I apologize for the newbie question, but when I write code involving Strings, it seems to compile half the time and fail half the time. I must not know what's really going on internally, so could someone explain it from the basics?

For instance, I write a function that takes a String as an argument. Strings are objects (containing arbitrarily large data) so you're not supposed to pass them by value, and pointers are supposedly bad news, so I use a reference:

void doSomething(String& s) { ... }

Then I try to call this elsewhere:

doSomething("/file/name.txt"); //doesn't compile

doSomething(String("/file/name.txt")); //doesn't compile

doSomething(new String("/file/name.txt")); //doesn't compile, and I don't want to make a new String, this is a memory leak!

doSomething(*new String("/file/name.txt")); //compiles...? what happened to that memory?

What's a better way to do this?


If you’re going to pass a constant string then you need:

void doSomething (const String& s) { … }


So you say your application doesn't compile. Do you read the errors the compiler spits out? For situations like this, even the MS compiler can be insightful.

For your current predicamment, Visual Studio 2013 displays the following: "error C2664: 'void someFunction(juce::String &)' : cannot convert argument 1 from 'const char [4]' to 'juce::String &'"

With some Google-Fu, MSDN's C2664 explanation goes into the possibilities in detail. Since I can't top the descriptions, here's the link: