ben said:
It is a good idea. Indeed it is what is happening with
heap-allocated objects:
int ref_to_num = *(new int); // heap allocation
ref_to_num = 1; // OK
delete &ref_to_num; // End the life of object referenced by
Undefined behaviour -- ref_to_num is an automatic int,
you copied the value of it from the int created with (new int)
which has now been leaked.
ref_to_num = 2; // undefined behavior, probably a crash
Fine, actually.
Also, this example (even if you modified it to: int &ref_to_num)
has nothing to do with the original topic (extension of
lifetime of temporaries). *(new int) is not a temporary.
Fact 1. Temporary object must be popped from the stack.
There is no need for a 'stack' of any sort to be present.
So this is not really a fact.
Fact 2. If an object is popped, it must be properly destroyed (by
calling the destructor).
You mean, if an object is deallocated it must be properly
destroyed. Which goes without saying. (Note: this 'fact' is
irrelevant, as temporary objects need not be deallocated,
see 'fact 1').
Consequently, a temporary object must be destroyed before the next
statement.
That doesn't follow from anything you just said.
There would be no contradiction if temporary objects lasted
until the end of the current block, for example.
In fact, that is exactly what happens when the temporary
object gets bound to a reference.
If you want to explicitly management the object's lifetime
with a reference, heap allocate the object.
Deeper and deeper into non-sequitur territory. If you want to
manage the lifetime with a reference.... use a reference!
Heap allocation has different semantics than automatic
allocation, as you have already noted.