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