-1

I came across codebase, where "moving ownership" through move semantic is used very frequently to deallocate resources. Example:

void process_and_free(Foo&& arg) {
  auto local_arg = std::move(arg);
  ...     // Use local_arg
}

void caller() {
  Foo foo;
  process_and_free(std::move(foo));
  ...
}

If there are some movable/dynamic resources in Foo after calling process_and_free, they will be deallocated (they will be moved to local_arg, which runs out of scope inside process_and_free). So far so good...

However, I was wondering what happens, if local_arg is not created:

void process(Foo&& arg) {
  ...     // Use arg everywhere
}

Will the resources in Foo be deallocated in this case as well?

Second question: do you think, is it a good SWE style to use processing methods to deallocate dynamic resources of the passed argument? I was reading that the move semantics does not guarantee moving of dynamic resources: supposedly they can be moved but don't have to. Hence, IMHO it may be ambiguous in which state foo is after process_and_free call...

I think for code reader/reviewer it may be more obvious, if the resources are deallocated inside the caller:

void caller() {
  {
    Foo foo;
    process_and_free(foo);
  }
  ...
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Marek
  • 79
  • 1
  • 6

1 Answers1

0

Answering both questions:

  1. Without creating the local_arg variable, the resources will not be moved, i.e. the Foo&& arg argument does not take ownership of the resources during process(std::move(foo)) call.
  2. Because the resources are not moved in the second example, IMHO it looks to me as a bad and confusing coding style. The reason is that looking only at the call process(std::move(foo)), the reader doesn't know what happens with foo without reviewing also process (btw. if process is a member method, it can be const with the same effect):
void process(Foo&& arg) const {
  auto local_arg = std::move(arg);
  ...
}
Marek
  • 79
  • 1
  • 6