← Back to context

Comment by tsimionescu

19 hours ago

It is absolutely knowable statically if ownership will be taken. It's not necessarily very easy to do so, but the decision is 100% up to the compiler, as part of overload resolution and optimization choices (like the NRVO analysis that the article mentions). Since ownership is an inherently static concept, it doesn't even make sense to think about "runtime ownership".

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`.

      2 replies →

    • > 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);
              }
          }

      13 replies →

I don't understand the downvoted here. Either the compiler emits the code to call a move constructor or it doesn't.

  • Static analysis is about proving whether the code emitted by a compiler is actually called at runtime. It's not simply about the presence of that code.

    Code can be emitted but never executed.

    • >Static analysis is about proving whether the code emitted by a compiler is actually called at runtime.

      That is but one thing that can static analysis can prove. It can also prove whether source code will call a move contractor or a copy constructor. Static analysis is about analyzing a program without actually running it. Analysizing what code is emitted is one way a program can be analyzed.

      2 replies →