C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Functions that don't need parentheses to make a call

From: Fabio Alemagna <falemagn_at_[hidden]>
Date: Tue, 25 Jul 2023 09:25:38 +0200
Il giorno mar 25 lug 2023 alle ore 00:24 Frederick Virchanza Gotham
via Std-Proposals <std-proposals_at_[hidden]> ha scritto:
>
> You'll occasionally see the following inside C++ files:
>
> MyClass &GetMyClass(void)
> {
> static MyClass obj;
> return obj;
> }
>
> #define g_obj (GetMyClass())
>
> Since C++11, this code uses a "once_flag" behind the scenes to make
> sure that it's threadsafe.
>
> The only problem here with using the preprocessor to define 'g_obj' is
> that we can't control the scope -- we can't put 'g_obj' inside a
> namespace. We also need to make sure that nobody names anything
> 'g_obj' anywhere.
> [...]

IANALL, but I don't think changing the language can be justified by
the need to avoid having to type two characters (the parenthesis of
the function call).

Is

    g_obj.foo()

So much better than

   g_obj().foo()?

Besides, one could always write

    static inline struct {
        MyClass *operator->() {
            return &GetMyClass();
        }
    } g_obj;

And save on one character:

    g_obj->foo();

Fabio

Received on 2023-07-25 07:25:51