Why does C ++ not implement construction + calling functions on a single line?

I am wondering why C ++ (and possibly other languages, I'm not sure) does not allow such statements.

MyObject foo.DoBar();

You might think that a language can understand to build an object, and then call a function. The only reason I can think that this does not work is that if the construction of the object failed, the operator will still try to call the function.

What are the reasons why those who help develop and integrate new features in C ++ (and possibly other languages) do not allow this?

+3
source share
4 answers

You can build an object and immediately call a function on it, you simply cannot assign the object to a variable if you do this:

MyObject().DoBar();

, , , , , , . , .

, , , .

+13

, - ? :

MyObject foo;
foo.DoBar();

. ( , ). , , " ". , , , .

, . , ?

:

" , , ".

, ? , , , . .

:

struct MyObject
{
    MyObject(bool pCallDoBar = true)
    {
        if (pCallDoBar)
            DoBar();
    }

    void DoBar(void)
    {
    }
};

MyObject foo;

:

MyObject().DoBar(); // destructor called here, though

, , .

+3

++. , , (, std::unordered_map ). . .

C , , ( ), , . , - . , , , .

" ?" " ?" , , ; - , .

, , ( ). ? void this? , , , ++, .

+2

: , foo , .

MyObject foo(arg1, arg2).DoBar();

,

MyObject foo(arg1, arg2);
foo.DoBar();

: !

Note that it is possible to do what you want if DoBar returns a link to *this:

MyObject foo = MyObject().DoBar();

With C ++ 0x move constructors, this will lead to a little overhead, but until then expects a false copy.

0
source

Source: https://habr.com/ru/post/1729172/


All Articles