Operator precedence of "new"

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Oct 15 08:43:21 PDT 2010

Related: A nice alternative for quickly using anonymous objects is
using the with statement, e.g.:

with (new Foo)
    // ... more code

And after the with block the object doesn't exist anymore. Or you
could bind it to some internal reference and keep it there, which
wouldn't destroy it after exiting the with block. Many of the DFL GUI
library code samples work this way, and it's quite a nice syntax imo.

On 10/15/10, Stanislav Blinov <blinov at loniir.ru> wrote:
>   15.10.2010 17:07, Stanislav Blinov пишет:
>>  15.10.2010 16:12, bearophile пишет:
>>> Currently to call a method to a newly build object/struct you need:
>>> (new Foo).bar();
>>> But isn't it better to change the D operator precedence rules a bit
>>> and allow new to bind more closely than the method call, to allow a
>>> syntax like:
>>> new Foo.bar();
>>> Do you see bad side effects in this D2 change?
>> Aside from what was already mentioned about nested classes:
>> What if bar() is a static function of Foo? Current precedence allows
>> the compiler to bug you if you write
>> new Foo.bar();
>> If precedence is modified in the way you propose, then you effectively
>> get a call to static function through an instance (which in itself is
>> valid operation), though that instance is immediately thrown away.
> Forgot to mention the 'bad' side:
> Despite you actually do throw instance away as a result of such call, in
> case of non-static method it is done intentionally and with keeping in
> mind precisely what does Foo's ctor do, while in case of static call
> instance construction may be unexpected and lead to subtle
> difficult-to-trace bugs.

More information about the Digitalmars-d-learn mailing list