Кога трябва да връщаме функция като референция
Здравейте,
Започнах да се обърквам със връщането на функции като референции. Не мога да си обясня точно кога трябва и кога не трябва. Знам, че при operator overloading използваме референции, когато искаме да направим chaining (но това не мога да си го обясня как точно работи), също знам, че i/ostream op. overloading могат да се използват само с референции. Но има други случаи, в които кода ми връща същия резултат без значение дали някои от функциите са били подадени като референции или не.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <sstream>
class Company {
public:
	Company(int id, const std::string& name, const std::vector<std::pair<char, char>>& employees);
	std::vector<std::pair<char, char>> getEmployees() const;
	//const std::vector<std::pair<char, char>>& getEmployees() const;
	std::string toString() const;
	std::string operator+(const std::string& s) const;
	Company& operator+=(const std::pair<char, char>& employee);
	//Company operator+=(const std::pair<char, char>& employee);
private:
	int _id;
	std::string _name;
	std::vector<std::pair<char, char>> _employees;
};
Company::Company(int id, const std::string& name, const std::vector<std::pair<char, char>>& employees)
	: _id{ id }, _name{ name }, _employees{ employees } {}
std::vector<std::pair<char, char>> Company::getEmployees() const {
	return _employees;
}
std::string Company::toString() const {
	std::ostringstream stream;
	stream << _id << " " << _name << " ";
	for (size_t i = 0; i < _employees.size(); ++i) {
		auto initials = _employees[i];
		stream << initials.first << initials.second;
		if (i < _employees.size() - 1) {
			stream << " ";
		}
	}
	return stream.str();
}
std::string Company::operator+(const std::string& s) const {
	return toString() + s;
}
Company& Company::operator+=(const std::pair<char, char>& employee) {
	_employees.push_back(employee);
	return *this;
}
int main() {
	Company c(42, "Something Inc.", { {'G', 'L'}, {'A', 'B'}, {'N', 'M'} });
	c += {'W', 'P'};
	std::cout << c + "<- this is a cool company" << std::endl;
	return 0;
}
Ето в горния код примерно мога да върна std::vector getEmployees() и operator+=() функциите със референция или без референция и кода сякаш работи по същия начин, но не знам как е по правилино.
Поздрави,
Виктор
Благодаря за отговора.