When deciding whether to return by value or by reference, consider these guidelines:
Here's an example of each:
#include <string>
// Returns by value
std::string getNameValue() { return "John"; }
// Returns by const reference
const std::string& getNameConstRef() {
static std::string name = "John";
return name;
}
// Returns by non-const reference
std::string& getNameRef() {
static std::string name = "John";
return name;
}
int main() {
std::string name1 = getNameValue();
const std::string& name2 = getNameConstRef();
std::string& name3 = getNameRef();
// Modifies the static variable in getNameRef
name3 = "Steve";
}
In general, prefer returning by value unless you have a good reason to return by reference.
Answers to questions are automatically generated and may not have been reviewed.
Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.