Re: non-const reference and const reference
"Victor Bazarov" <v.Abazarov@comAcast.net> wrote in message
news:fk69pq$pti$1@news.datemas.de...
Ben Voigt [C++ MVP] wrote:
"George" <George@discussions.microsoft.com> wrote in message
news:593CA7FA-6B65-452D-B2D1-7486F3435D14@microsoft.com...
Hello everyone,
This is my understanding of non-const reference, const reference and
their relationships with lvalue/rvalue. Please help to review
whether it is correct
and feel free to correct me. Thanks.
1. A const reference can be binded to a rvalue, for example, a
temporary object. And the "life" of the temporary object is
guaranteed to be extended
and we can safely operate through the const-reference.
No, the lifetime of the temporary object is only extended up to a
limit (the enclosing block), certain uses are not safe.
The limit you're talking about is the lifetime of the reference.
If I create a dynamic object with a member that is a reference to
T and initialise that reference with some temporary of type T,
and then I never delete that dynamic object, the temporary should
survive until the program ends (regardless of scopes, etc.)
This IS what I was talking about in my second point, if I understand you
correctly.
Are you saying this is safe?
class MakeARef
{
const std::complex<double>& m_ref;
public:
// here we use a reference to bind a member reference in a
ctor-initialization-list, which I think is bad news if the reference is to a
temporary
MakeARef(const std::complex<double>& ref) : m_ref(ref) {}
};
MakeARef* f(std::complex<double> v)
{
return new MakeARef(v + 1);
}
You're saying that the compiler magically allocates extra memory when
calling operator new, to hold the temporary? And also magically frees the
extra memory when the referent is deleted?
How about using in-place initialization? Still extra memory reserved and
allocated?
I'd appreciate a reference to the relevant section of the standard.
Especially returning such a reference is not safe (as you posted in a
subsequent thread).
Returning a reference initialises another reference. Often the
actual event of initialising another variable or temporary is
missed by the programmer; the binding to a temporary established
at some point does not survive (and is not transferred by)
initialising some other, unrelated, reference.
Also using such a reference to bind a member reference in a
ctor-initialization-list is not safe.
Not sure what you mean by this, so no comment.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask