Martin wrote 10 lines
On 01/11/2013 15:10, Tomas Hajny wrote:
> Sorry if I overlooked something, but where is the variable of that type
> declared in your code? These objects may be either declared statically
> ("var B: TBar") or dynamically ("Result := New (TBar.Init)" - but then
> the
> return value must be of type PBar, not TBar).
Objects are like (advanced) records.
So Result is a TBar, and result already has the memory it needs. "New"
is not needed.
Result is stored in a temporarily allocated memory. You are right that New is not absolutely needed (as witnessed by the compiler accepting your code
- unlike TP/BP which wouldn't accept TBar as return value, because it doesn't support performing assignment on objects or even records), but using the temporarily allocated memory implies that you initialize the memory in one place first (Init) and then you need to copy the data to another memory location afterwards. Depending on the object size, this may or may not be an issue, but it doesn't look like the most efficient solution to me in any case.
Show quoted text 8 lines
> If I understand it
> correctly, you initialize the object on the stack, but it would
> disappear
> from there (gets overwritten) immediately after the function return (the
> following function call would overwrite it).
It gets lost only, because i do not use the result of the function call.
But even if D did "SomVarBar := Foo;", I still get the warning.
Yes. Still, if the (formally incorrect) warning helps in pointing out that the chosen solution may not be the most efficient one, it isn't so bad from my point of view. ;-)
Tomas