Given a function which returns a heavy-to-construct and heavy-to-destroy object, is there a way to skip object construction and destruction if the function return value is not consumed?
HeavyObject func();
auto res = func(); // heavy object is constructed and returned
func(); // lightweight "null" object is returned and immediately destroyed
Is there a technique which I can use except tag dispatching like void func(NotConsumed);
?
Update
It is okay to discard the return value, so [[nodiscard]]
is not an option. Clients can decide if they want to use the result or not.
Let's assume func()
initiates some job and HeavyObject
serves as a some sort of handle. Clients can use it later to control/monitor the job, if they want to. Construction of such handle could involve e.g. creating pipes or heap memory allocation.
There are other overloads of func()
where the return value must be consumed and which are marked as [[nodiscard]]
. The new overload does not have this requirement but must be compatible with existing API.