Move in C++ without a std:move

(andreasfertig.com)

27 points | by dalvrosa 1 day ago

6 comments

  • boguscoder 1 minute ago
    Title made me think they’d just show that move is just a simple cast, nothing more
  • ptspts 4 minutes ago
    The HN title is incorrect. It should contain std::move.
  • tom_ 2 hours ago
    If the author is reading: both complicated examples are the same.
    • quuxplusone 2 hours ago
      Yeah, the second one is supposed to read `Apple&& Cat(Apple&& val) { return val; }` — but the return type's `&&` was omitted by accident.
    • dkenyser 51 minutes ago
      I swear I was staring at these two examples for longer than I care to admit wondering if I was just blind or dumb or both.
  • fluoridation 2 hours ago
    Unfortunately, I don't think there's getting away from just understanding value semantics to get the correct and/or performant behavior.
  • sprocketz 1 hour ago
    What is that makes NVRO so much more difficult to implement? Why couldn't they mandate that just like RVO? Do compilers literally just special case a simple return statement of a direct construction or something?
    • bluGill 1 hour ago
      The simple cases are simple. However the complex cases get hard.

          mytype foo() {
             mytype one;
             ...
             if(something) {
                mytype two;
                ...
                return two;
             }
          return one;
          }
      
      Is going to be much harder because you don't know are compile time which is returned and so cannot construct the one you return in the correct place. That is just off the top of my head, I'm not a compiler writer, I'm sure they have figured out the simple versions of the above, but you can start to see the complex versions that they can't.
    • dataflow 1 hour ago
      The point of (N)RVO is to directly construct the return value in-place at the calling frame. Which requires knowing what object will land there.

      In RVO there is no problem because you know what object is the one you need to put there.

      In NRVO there is a problem because you might have one of multiple objects being returned and you need to know which one to construct at the call site; it can't be all of them on top of each other. But you don't necessarily know at the time of construction whether that object will be the one that is actually returned. Doing so requires imperfect code analysis so the standard would need to define the complicated analyses to perform.

    • fluoridation 1 hour ago
      N/RVO works by (at the machine language level, of course) rewriting the function signature to return void and take an extra pointer parameter, which is written to before returning. If you're returning a newly-constructed object, the compiler can rewrite that into calling the constructor on the pointer, but if you're returning a named object, the class may have a non-trivial destructor that needs to run after the move, such that it's not possible to rewrite uses of the local object into uses of the pointer.

      I'm not too confident on that last part, because such an implementation would mess with semantics in case of an exception, so anyone feel free to correct me on that.

      • jcranmer 47 minutes ago
        I'm sorry, this comment is completely wrong.

        NRVO does not affect the ABI of the function. It cannot affect the ABI, for whether or not it kicks in depends on the body of the function, and affecting the ABI would make it impossible to use it if only the declaration appears in a header.

        The correct explanation is this:

        In C++, classes with nontrivial destructors or copy/move constructors are considered nontrivial for the purposes of calls and are passed via pointers rather than via value. By passing via pointer, the class has a stable address and thus 'this' pointer. Returning such a class means the caller allocates the storage for the class on the stack before calling the function, and passes the pointer to that storage to the function as an extra parameter. This is based solely on the definition of the class itself; this happens whether or not NRVO kicks in.

        Usually, when you declare a variable, the abstract machine of C++ requires you to construct a new object and call the copy/move constructors or assignment operators and the destructors at various times as appropriate. With nontrivial versions of these special functions, it is possible to observe whether or not they were called (these things still happen with trivial classes, but it's not so easy to observe). Returning a value requires constructing the storage space for that object--with all the attendant abstract machinery that involves.

        What NRVO does is to say that, under certain conditions, rather than constructing storage space for a given variable that is normally required, the storage space that is allocated for the return value by the ABI is used instead. In essence, you are promoting a given variable to the return value hence the name 'Named Return Value Optimization'. What makes this annoying to implement is that you have to track at the AST level, before doing any code generation at all, whether or not a given variable is eligible for NRVO, and then use that information to control the code generation for allocating storage space.

        Despite its name, NRVO is not actually an 'optimization' in the compiler. The optimizer plays no role in it, since the optimizer is fulfilling the requirements of the abstract machine. Instead, it is a set of conditions that allows the frontend to omit calls to copy constructors, etc. under specific circumstances.

      • dataflow 1 hour ago
        > N/RVO works by (at the machine language level, of course) rewriting the function signature to return void and take an extra pointer parameter

        This sounds wrong, are you sure? Would you mind demonstrating with an example on godbolt? Whether NRVO applies or not, the ABI should be the same, AFAIK.

        • OskarS 1 hour ago
          Yes, it works exactly like this, this is a demo on godbolt [0]. rdi stores the pointer in both cases, makeS1() uses RVO, makeS2() takes it explicitly and constructs with placement new.

          I will say before testing this i didn't realize the RVO calling convention was to return the pointer you pass in, but apparently so. If makeS2() returned void, it's just a tail call to the constructor, but makeS1() has to spill rbx and use it to save the pointer.

          [0]: https://godbolt.org/z/ovd1n99P8

        • fluoridation 1 hour ago
          Yes, of that I'm sure. This optimization is only possible if the compiler has control of both sides of a call. If the function may be callable from other translation units or modules I imagine it generates a thin wrapper that's externally callable.
          • dgrunwald 57 minutes ago
            The optimization is often possible even if the computer does not see the call, because most (all?) ABIs have always required hidden pointer parameters for class types with non-trivial destructors.

            https://godbolt.org/z/9WvnEvEYh Note how `std::unique_ptr<int>` effectively passed as a `int**`; and that the by-value unique_ptr is not destroyed at the end of the function -- destroying parameters is instead the caller's job (and commonly only happens at the end of the full expression containing the call -- though this choice is implementation-defined). But that can only work if the caller can see the updated value of the parameter (to avoid double-free for `clear`) -> thus the need to pass the parameter by hidden pointer.

    • whizzter 1 hour ago
      RVO is easy to detect since it happens only in expressions in return-statements.

      NRVO requires the compiler to analyze the flow, like if 2 different variables/constructions can lead to the return (what one do we take, or can we do either later?).

      Also, with RVO it's easy to detect and elide destruction calling for things going out of scope whilst NRVO would require more careful management of destruction order,etc.

      Basically, NRVO touches a lot of things in "inconventient" places that can easily require reworking internal compiler structures to track destinations whilst RVO was probably far easier to just "hack in".

      • sprocketz 1 hour ago
        I figured any half decent compiler already do plenty of flow and liveness analysis on everything for register allocation, dead code elimination and what not.

        Maybe it's the guaranteed elision that makes it a problem, like you can't fail the analysis, but then maybe you go the rust route - fail to compile and urge the programmer to rewrite their code so it accepts it.

        Make it opt in with [[must_elide]] so old code still works I guess.

    • locknitpicker 1 hour ago
      > What is that makes NVRO so much more difficult to implement?

      I recall reading that at a high level RVO is implemented by treating the return value as an external object. In simple terms (simplistic terms) RVO then works by

      - first instantiating the return variable,

      - passing the var by reference to the function,

      - and then use return value to actually initialize the variable passed by reference.

      The moment there's some funny logic on what to write to that output value, the problem gets far more complex.

  • hn45e7pbij 1 day ago
    I'd push back slightly on move — at small scale the opposite has been true for me.
    • jplusequalt 9 minutes ago
      Thanks Claude.
    • dalvrosa 1 day ago
      Not sure what you mean, but std::move is one of the greatest tools in C++
      • pdpi 1 hour ago
        This is one case where Rust benefited from C++’s experience — move by default with opt-in clone/copy is IMO the better setup.
        • sprocketz 1 hour ago
          And the most important idea: destructive moves. Since C++ doesn't track lifetimes it has to leave the object in a "valid state" after a move and the destructor still runs which has to have a check if it should do something or not.
          • pornel 13 minutes ago
            BTW, Rust's lifetime annotations for borrowed references are a mostly orthogonal feature.

            Liveness of objects for move/drop semantics is tracked differently, without any syntax and with implicit runtime drop flags where necessary.

            C++ could probably add the same deinitialized/moved-from state tracking (with an opt-in for back compat sake) purely to avoid dtor bloat, without having to add safety of borrow checking.

            • bluGill 6 minutes ago
              > C++ could probably add the same deinitialized/moved-from state (with an opt-in for back compat sake) purely to avoid dtor bloat, without having to add safety of borrow checking.

              There is a lot of talk in the C++ committee about this. The details are complex in some obscure cases.

        • affenape 1 hour ago
          It did for sure, but the problem with C++ is its heritage, specifically that structures can be self-referential. For instance, the Rust's url::Url type has to use usize offsets for tracking the location of each of its components. Conversely, in C++, someone could have already created a similar Url type that would use std::string for the buffer and char pointers for the component locations. As such, you cannot simply memcpy from one struct into another and forget the former as std::string could have its own in-place storage and that would invalidate all pointers - you'll need to define a move constructor instead.
      • bluGill 1 hour ago
        std::move is a great tool when used correctly. However used incorrectly it makes code worse: more verbose and less performant. Since I have no idea how you are using it I can't comment on your experience. My experience is people (including me!) get it wrong fairly often. Fortunately tools can detect a lot of cases where you get it wrong.
        • sprocketz 7 minutes ago
          My little trick is to think of them as "oh, I accidentally made an lvalue from an actual rvalue here because a name was introduced, so I need to cast (i.e move() or forward()) back to an rvalue again", that's why i have them as macros: MOVE_CAST and FORWARD_CAST defined as static_cast (also avoids blowing up compile times). I never think in terms of "moving this object".