Evo strings and containers use Sharing so copying is generally efficient (though see warning about thread safety).
This shows the preferred ways of passing a string with Evo.
- Passing a string as an argument (by const reference):
...
}
int main() {
foo("test");
return 0;
}
- Passing a string by value works but is not ideal (less efficient):
- Best to "return" a string using an "out" parameter (by reference):
- You can also return a string by value, but this is not ideal (less efficient):
- Note that circumstances may allow compiler Return Value Optimization (RVO), but you have to assume the compiler is able to do this and there are cases where it can't (where the compiler will silently return by value) – sticking with an out parameter for consistency and simplicity is recommended
These suggestions also apply in general to Evo containers like List, and other complex objects.
For passing read-only strings it's often useful to use SubString to show how the string is used. A function taking a SubString argument explicitly shows the string is read-only and prevents further Sharing when copied to another String (i.e. sharing stops here), and is often useful in multithreaded situations (with sychronization as needed).
- Pass substring as an argument (by const reference):
struct MyData {
data = str;
}
};
int main() {
MyData data;
data.store(str);
data.store("testing");
return 0;
}
- As with String, passing SubString by value works but is not ideal (less efficient)
- Returning a SubString in any way is often dangerous, unless returning one of the arguments
const SubString& foo(const SubString& str) {
...
return str;
}
Alternatively, for passing read-only strings with STL Compatibility use StringBase. This works the same way as SubString.
- Pass substring as an argument (by const reference) using StringBase :
#include <string>
struct MyData {
data = str;
}
};
int main() {
MyData data;
data.store(str);
std::string stdstr("testing");
data.store(stdstr);
return 0;
}
- StringBase is only used for passing strings to functions (and only by const-reference)
- See STL Compatibility
See also: Unsafe Pointer Referencing