References in C++ are baffling me. :)
The basic idea is that I\'m trying to return an object from a function. I\'d like to do it without returning a pointer (because
One potential solution, depending on your use case, is to default-construct the object outside of the function, take in a reference to it, and initialize the referenced object within the function, like so:
void initFoo(Foo& foo)
{
foo.setN(3);
foo.setBar("bar");
// ... etc ...
}
int main()
{
Foo foo;
initFoo(foo);
return 0;
}
Now this of course does not work if it is not possible (or does not make sense) to default-construct a Foo
object and then initialize it later. If that is the case, then your only real option to avoid copy-construction is to return a pointer to a heap-allocated object.
But then think about why you are trying to avoid copy-construction in the first place. Is the "expense" of copy construction really affecting your program, or is this a case of premature optimization?