Re: pointer vs non-pointer
worlman385@yahoo.com wrote:
On Tue, 22 Apr 2008 12:10:14 +0200, Ulrich Eckhardt
It depends on what type of object it is. There are objects that
behave like values (std::string, float etc) and others that behave
like entities (std::fstream, CWnd etc). Value types can be copied
and so can be returned from functions. The original object only
lives inside the function, but its value is transferred to the
caller in a copy. Entity types can not be copied, so if you need
to return them from a function, you have to allocate them
dynamically.
So, if I want to return an object created in a function I better use
dynamic creation?
No, it is not really that simple.
MyCar myfunction(){
MyCar mycar;
return mycar;
} // this is return by value
// this is more expensive as it copy whole value and return value
You also have to consider what is expensive. Does MyCar contain two
integers? Then it is not expensive.
There are also special rules in language that will let the compiler
optimize this case
MyCar BMW = myfunction();
so that the result is constructed directly into the BMW variable,
avoiding the copying of the return value.
MyCar* myfunction(){
MyCar* mycar = new MyCar();
return mycar;
} // this is return by reference(pointer)
// less expensive as it only return 4 byte = pointer.
Or a pointer could be 8 bytes on a 64-bit system - larger than an int.
Accessing the car through a pointer for the rest of the program
perhaps adds an additional cost.
Also, who said that dynamic allocation is free? Often new is much more
expensive than a simple return!
Also for a collection of object like a LinkedList object, since it's
very expensive to return by value, i must use return by
reference(pointer):
LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
} // this is return by reference(pointer)
// less expensive as it only return 4 byte = pointer.
// instead of return by value to copy all element in the List
But the return value optimizations (RVO/NRVO) allowed by the language
might let the compiler avoid copying the result.
Also, why are you constructing the linked list inside a fucntion?
Perhaps you can place it somewhere, like inside a class that uses it,
so that it doesn't have to be copied at all.
Bo Persson