reference operator


why it is necessary to use the reference operator here ?
const string& content() const {return data;}

Example in http://www.cplusplus.com/doc/tutorial/classes2/
// classes and default constructors
#include <iostream>
#include <string>
using namespace std;

class Example3 {
string data;
public:
Example3 (const string& str) : data(str) {}
Example3() {}
const string& content() const {return data;}
};

int main () {
Example3 foo;
Example3 bar ("Example");

cout << "bar's content: " << bar.content() << '\n';
return 0;
}
I wouldn't classify a reference as an operator more of a special type of variable. As far as that particular case you don't need to return it as a reference but the string could be very heavy so it is best to pass it as a reference and to make it a rvalue only you would need to make it constant.
What giblit says. It's to avoid copying the string unnecessarily.
Topic archived. No new replies allowed.