C++ references are still confusing to me. Suppose I have a function/method which creates an object of type Foo
and returns it by reference. (I assume that if I want to return the object, it cannot be a local variable allocated on the stack, so I must allocate it on the heap with new
):
Foo& makeFoo() {
...
Foo* f = new Foo;
...
return *f;
}
When I want to store the object created in a local variable of another function, should the type be Foo
void useFoo() {
Foo f = makeFoo();
f.doSomething();
}
or Foo&
?
void useFoo() {
Foo& f = makeFoo();
f.doSomething();
}
Since both is correct syntax: Is there a significant difference between the two variants?