← Back to context

Comment by adrianN

17 hours ago

My function can choose to move or not to move from an object based on io input.

Can you show an example of what you mean?

My claim is that, if I call `foo(std::move(myObj))`, it is statically knowable if `foo` receives a copy of `myObj` or whether it is moved to it. Of course, `foo` can choose to further copy or move the data it receives, but it can't choose later on if it's copied or not.

Now, if I give `foo` a pointer to myObj, it could of course choose to copy or move from it later and based on runtime info - but this is not the discussion we are having, and `std::move` is not involved from my side at all.

  • No, it is not statically knowable if it is actually moved.

        void foo(Obj && arg) {}
    

    Does not move `arg`. It's fairly easy to write code that assumes `std::move` moves the value, but that can lead to bugs. For example:

        void some_function(std::vector<int> &&);
        void some_function2(std::vector<int> &&);
    
        void main() {
            std::vector<int> a = { 1 };
            some_function(std::move(a));
    
            a.push_back(2);
            some_other_function(std::move(a));
        }
    

    The expectation is that `some_other_function` is always called with `{ 2 }`, but this will only happen if `some_function` actually moves `a`.

    • Is pushing to a moved-from vector even legal? I thought in general the only guarantee you have after a move is that is save to destruct the object.

      1 reply →

  • > Can you show an example of what you mean?

        void foo(std::unique_ptr<int, Deleter>&& p) {
            std::random_device rdev {};
            auto dist = std::uniform_int_distribution<>(0, 1);
            if (dist(rdev)) {
                auto pp = std::move(p);
            }
        }

    • This is exactly what I meant as irrelevant.

      If I call `foo(std::move(my_unique_ptr))`, I know for sure, statically, that my_unique_ptr was moved from, as part of the function call process, and I can no longer access it. Whether `foo` chooses to further move from it is irrelevant.

      12 replies →