Take the following snippet of code
#include <iostream>
#include <string>
class Foo {
private:
std::string m_name;
public:
Foo(std::string name) : m_name { name } {}
const std::string & get_name() const { return m_name; }
};
int main() {
Foo x { "bob" };
x.get_name();
}
Because I initialized an object and name
exists somewhere in memory, is a temporary object is made when I call the x.get_name()
? If a temporary object is made, than is there a point to returning by reference? My understanding is you return by reference so to avoid the cost of creating a large object or when using an std::ostream&
object because you have to.