logoalt Hacker News

1718627440yesterday at 12:31 AM1 replyview on HN

> Unfortunately, this is not possible in C++, so the user has to move explicitly (with std::move).

Honestly why not? A locally used variable sounds to be very much something the compiler can reason about. And a variable only declared in a loop, which is destroyed at the end of each iteration and only read from should be able to be optimized away. I don't know Rust, I mostly write C.


Replies

spacechild1yesterday at 1:10 AM

Yes, this could work for simple cases, but this breaks down pretty quickly:

  void checkFoo(const Foo&);
  
  Foo getFoo();
  
  void example() {
    std::vector<Foo> vec;

    Foo foo = getFoo();
    if (checkFoo(foo)) {
      // *We* know that checkFoo() does not store a
      // reference to 'foo' but the compiler does not
      // know this. Therefore it cannot automatically
      // move 'foo' into the std::vector.
      vec.push_back(std::move(foo));
    }
  }
The fundamental problem is that C++ does not track object lifetimes. You would end up with a system where the compiler would move objects only under certain circumstances, which would be very hard to reason about.
show 1 reply