Manfred writes:
> My earlier reference to object lifetime was not by accident. What you are
> trying to achieve appears to be some ownership model wherein a contained
> object may survive its container.
Actually, it's the opposite: the contained object may not survive its
container.
And in case of std::unique_ptr, it's guaranteed not to survive its container.
> Indeed not, but then if ownership is allocated to std::unique_ptr, then it
> is better to manage the entire object lifetime through such unique_ptr,
> instead of splitting this responsibility between container and contained.
It is true that (in this context) one can explicitly assign the container,
and thus preserve ownership:
auto office=building.penthouse();
const auto &available_hours=office->get_available_hours();
Here, the returned value from build.penthouse() is assigned to "office". The
returned value happens to be a unique_ptr, but I don't really care. My
contract, is that penthouse() returns a container for an office of some kind
that implements get_available_hours() whose lifetime exists as long as the
object that implements get_available_hours() exists.
I can't do
const auto &available_hours=building.penthouse()->get_available_hours();
This will leave me with dangling reference. Instead I have to assign
whatever penthouse() returns to an auto, and then dereference it. And then
this auto object exists until the end of the scope too, which might have
other side effects, as well.
But suppose you could overload -> so that it ends up calling either an & or
an && overload in the contained object, depending upon whether the container
itself is also & or &&. Then what we can do now? Well:
const auto &available_hours=office->get_available_hours();
This still calls the regular & overload, which returns the same const reference,
to the avilable hours. But now:
const auto &available_hours=building.penthouse()->get_available_hours();
Much shorter, cleaner, and to the point. This uses the currently non-
existent mechanism to invoke the && overload, which returns a prvalue
instead of a const reference. Its lifetime now gets automatically extended,
as per the current rules of doing so.
Also: whatever object penthouse() returned has served its purpose, and can
go away, and it doesn't have to exist until the end of the scope.
But, to achieve the same results right now, one has to do
(*building.penthouse()).get_available_hours(), employing the operator*
overload in penthouse's returned object, which returns an && instead of &.
This is fugly.