Hacker News new | ask | show | jobs
by daoxid 2633 days ago
> In general, if I need an rvalue and it's legal to convert the lvalue I have into an rvalue, the compiler should do it automatically.

This is already done in some places. Example:

    std::unique_ptr<int> get_int() {
        auto p = std::make_unique<int>(1);

        // `p` is an lvalue but treated as an rvalue in the return statement.
        // (This would not compile otherwise because `p` is not copyable.)
        return p;
    }
2 comments

Yes RVO is one case where the compiler will do it automatically.

I think copy initialization of an object will have the same will apply copy elision as well to result in the same performance, but I'm not entirely sure.

That is the right approach IMO. What I'm basically saying is "more of this". It's clearly possible for C++ compilers to do this in many more cases. They already do most of the hard parts just to produce some of the error messages that they do. Why not use that knowledge more often to help the programmer instead of burdening them?
Because the compiler can't always know when moving a value is acceptable.
> It's clearly possible for C++ compilers to do this in many more cases. [...] Why not use that knowledge more often to help the programmer instead of burdening them?

Because it'd break code. I explained in another comment here: https://news.ycombinator.com/item?id=19634423

> Because it'd break code.

Then that's an indictment of the decisions that led to such code being written in the first place.

Only if you're quick to judge without understanding why such code is and will continue to be written.
You're pretty quick to assume I don't. Believe me, I understand. I just don't agree that it's a good idea to mix up object lifetimes and execution context by using destructors to "magically" release locks etc. It never was. The mistakes were made years ago.

I'm not quick to judge (in this case). I'm judging after careful consideration, because I know the difference between good and bad patterns. The ones being hasty are those who mistake their own comfort level with something (often because they know nothing else) for actual merit.

RAII is one of the core language feature of C++.

Replacing it with defer or GC will surely break existing programs.

It would make sense ONLY if you want to have a new language.

Your proposed better pattern to follow when one needs a finally block in C++ is...?